#!/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

if sys.prefix == '/usr':
    conf_path = '/etc/patchman'
else:
    conf_path = os.path.join(sys.prefix, 'etc/patchman')
    # if conf_path doesn't exist, try ./etc/patchman
    if not os.path.isdir(conf_path):
        conf_path = './etc/patchman'
local_settings = os.path.join(conf_path, 'local_settings.py')

chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'
settings_contents = codecs.open(local_settings, 'r', encoding='utf-8').read()
secret_key = ''.join([choice(chars) 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)
