#!/usr/bin/python
"""Read settings file and generate a SECRET_KEY if required."""
from __future__ import print_function
import os
import re
import io
from django.utils.crypto import get_random_string

main_settings_file = "/etc/karaage3/settings.py"
main_settings_file_tmp = "/etc/karaage3/settings.py.tmp"

old_settings_contents = io.open(
    main_settings_file, 'r', encoding="utf_8",
).read()

secret_key = get_random_string(
    50,
    'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)',
)

(new_settings_contents, n) = re.subn(
    r"^SECRET_KEY *= *''",
    "SECRET_KEY = '" + secret_key + "'",
    old_settings_contents,
    flags=re.MULTILINE,
)

# don't replace settings file if no changes to be made.
if n <= 0:
    raise SystemExit(
        "ERROR: SECRET_KEY already set (or not defined) in %r: aborting." % (
            main_settings_file,
        ),
    )

fp = io.open(main_settings_file_tmp, 'w', encoding="utf_8")
fp.write(new_settings_contents)
fp.close()

os.rename(main_settings_file_tmp, main_settings_file)
