#!/usr/bin/env python
#
# Copyright 2016 Marcus Furlong <furlongm@gmail.com>
#
# This file is part of Patchman.
#
# Patchman is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3 only.
#
# Patchman is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Patchman. If not, see <http://www.gnu.org/licenses/>

import os
import re
import sys
import codecs
from random import choice
from tempfile import NamedTemporaryFile
from shutil import copy
from pwd import getpwnam

if sys.prefix == '/usr':
    conf_path = '/etc/patchman'
else:
    conf_path = sys.prefix + '/etc/patchman'

local_settings = conf_path + '/local_settings.py'

settings_contents = codecs.open(local_settings, 'r', encoding='utf-8').read()
secret_key = ''.join([choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(50)])
settings_contents = re.sub(r"(?<=SECRET_KEY = ')'", secret_key + "'", settings_contents)

f = NamedTemporaryFile(delete=False)
temp = f.name
f.close()

fh = codecs.open(temp, 'w+b', encoding='utf-8')
fh.write(settings_contents)
fh.close()

copy(temp, local_settings)
os.remove(temp)
