#!/usr/bin/env python3

"""
Generate a 4096-bit Django SECRET_KEY and append it as a [secrets]
section to a config.ini. Use `config.ini' if the first argument does not
hold a path to a config.ini, and copy over `config.example.ini' if it
does not exist.
"""

import string
import os
from shutil import copyfile

population = string.ascii_letters + string.punctuation + string.digits
key_len = 512

print('Generating key...')
random_bytes = os.urandom(key_len)
# Work through the random data from /dev/urandom byte by byte, converting it to
# characters from population
key = ''.join(population[int(x / 256 * len(population))] for x in random_bytes)
secrets_section = """
[secrets]
secret_key = {}
""".format(key)

if not os.path.exists('config.ini'):
    print('config.ini does not exist, so copying over config.ini.example...')
    copyfile('config.example.ini', 'config.ini')

print('Appending [secrets] section with key to config.ini...')
open('config.ini', 'a').write(secrets_section)

print('Done!')

@@ -273,18 +273,44 @@
 %0Aimport 
-o
 s
+ys%0Aimport os%0Aimport os.path
 %0Afrom sh
@@ -417,16 +417,351 @@
  = 512%0A%0A
+# If user supplies first argument, use it as the path to the config.ini to%0A# write to, else use 'config.ini' in the current directory%0Aif len(sys.argv) - 1 %3E= 1:%0A    config_ini_path = sys.argv%5B1%5D%0Aelse:%0A    config_ini_path = 'config.ini'%0Aprint(%22Writing secret key to %22%0A      %22ini file %60%7B%7D'...%22.format(os.path.abspath(config_ini_path)))%0A%0A
 print('G
@@ -1090,28 +1090,31 @@
 .exists(
-'
 config
-.ini'
+_ini_path
 ):%0A    p
@@ -1118,27 +1118,21 @@
   print(
-'config.ini
+%22%60%7B%7D'
  does no
@@ -1160,27 +1160,36 @@
 ver 
+%22%0A          %22
 config.
-ini.
 example.
 ..')
@@ -1184,19 +1184,47 @@
 example.
-..'
+ini...%22.format(config_ini_path)
 )%0A    co
@@ -1252,28 +1252,31 @@
 e.ini', 
-'
 config
-.ini'
+_ini_path
 )%0A%0Aprint
@@ -1276,17 +1276,17 @@
 %0A%0Aprint(
-'
+%22
 Appendin
@@ -1321,22 +1321,49 @@
  to 
+%22%0A      %22%60%7B%7D'...%22.format(
 config
-.ini...'
+_ini_path)
 )%0Aop

Read config.ini path from argv[1]