#!/usr/bin/env python3
#
# Copyright 2016-2021 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 fileinput
import os
import site
import sys
from random import choice
from string import ascii_letters, digits

if sys.prefix == '/usr':
    conf_path = '/etc/patchman'
else:
    conf_path = os.path.join(sys.prefix, 'etc/patchman')
    # if sys.prefix + conf_path doesn't exist, try ./etc/patchman (source)
    if not os.path.isdir(conf_path):
        conf_path = './etc/patchman'
    # if ./etc/patchman doesn't exist, try site.getsitepackages() (pip)
    if not os.path.isdir(conf_path):
        try:
            sitepackages = site.getsitepackages()
        except AttributeError:
            # virtualenv, try site-packages in sys.path
            sp = 'site-packages'
            sitepackages = [s for s in sys.path if s.endswith(sp)][0]
        conf_path = os.path.join(sitepackages, 'etc/patchman')
local_settings = os.path.join(conf_path, 'local_settings.py')

chars = ascii_letters + digits + '!@#$%^&*(-_=+)'
secret_key = ''.join([choice(chars) for i in range(50)])

for line in fileinput.input(local_settings, inplace=True):
    if line.startswith('SECRET_KEY'):
        print('SECRET_KEY = \'' + secret_key + '\'')
    else:
        print(line.rstrip())
