#!/usr/bin/env python

import jinja2
import os
import random
import string

print("Bootstrapping Zues for local usage")

template_file = os.getenv("ZUES_SITE_LOCAL_SETTINGS_TEMPLATE_PATH", "zuessite/templates/local_settings_template.py")
template_file_full_path = template_file

local_settings_file = os.getenv("ZUES_SITE_LOCAL_SETTINGS_PATH", "zuessite/local_settings.py")
local_settings_file_full_path = local_settings_file

current_working_directory = os.getcwd()

print("Current working directory is", current_working_directory)

if current_working_directory.endswith("scripts"):
    parent_directory = os.path.abspath(os.path.join(os.getcwd(), os.pardir))
    template_file_full_path = "{}/{}".format(parent_directory, template_file)
    local_settings_file_full_path = "{}/{}".format(parent_directory, local_settings_file)

if os.path.isfile(template_file_full_path):
    print("File found in", template_file_full_path)
else:
    print("Local setting file not found. Exiting")
    exit(1)

print("Loading local_settings.py template")

template_loader = jinja2.FileSystemLoader(searchpath=".")
template_env = jinja2.Environment(loader=template_loader)
template = template_env.get_template(template_file_full_path)

print("Generating secret key")

secret_key = ''.join(random.SystemRandom().choice(string.ascii_lowercase + string.ascii_uppercase + string.digits) for _ in range(50))

print("Parsing template")

parsed_template = template.render(secret_key=secret_key)

print("Writing template")

with open(local_settings_file_full_path, "w") as f:
    f.write(parsed_template)
    f.close
