#!{{ python_executable }}

import cgi
import cgitb
import ConfigParser
import os

cgitb.enable()
form = cgi.FieldStorage()

print "<html><head>"
print "<link rel=\"stylesheet\" href=\"static/pure-min.css\">"
print "<link rel=\"stylesheet\" href=\"static/style.css\">"
print "</head><body>"

config_file = "{{ config_cfg }}"

if not os.path.exists(config_file):
  print "Your software does <b>not</b> embed 0-knowledge. \
  This interface is useless in this case</body></html>"
  exit(0)

parser = ConfigParser.ConfigParser()
parser.read(config_file)

if not parser.has_section('public'):
  print "<p>Your software does not use 0-knowledge settings.</p></body></html>"
  exit(0)

for name in form:
  if parser.has_option('public', name):
    parser.set('public', name, form[name].value)
with open(config_file, 'w') as file:
  parser.write(file)

if len(form) > 0:
  try:
    os.remove("{{ timestamp }}")
  except OSError:
    pass

print "<h1>Values that can be defined :</h1>"
print "<form action=\"/index.cgi\" method=\"post\" class=\"pure-form-aligned\">"
print "<input type=\"hidden\" name=\"posting-script\" value=\"{{ pwd }}/{{ this_file }}\">"
for option in parser.options("public"):
  print "<div class=\"pure-control-group\">"
  print "<label for=\"%s\">%s</label>" % (cgi.escape(option, quote=True), cgi.escape(option))
  print "<input type=\"text\" name=\"%s\" value=\"%s\">" % (cgi.escape(option, quote=True), cgi.escape(parser.get('public', option), quote=True))
  print "</div>"
print "<div class=\"pure-controls\"><button type=\"submit\" class=\"pure-button \
 pure-button-primary\">Save</button></div></form>"

print "<br><h1>Other values :</h1>"
print "<form class=\"pure-form-aligned\">"
for section in parser.sections():
  if section != 'public':
    for option in parser.options(section):
      print "<div class=\"pure-control-group\">"
      print "<label for=\"%s\">%s</label>" % (cgi.escape(option, quote=True), cgi.escape(option))
      print "<input type=\"text\" name=\"%s\" value=\"%s\" readonly>" %(cgi.escape(option, quote=True), cgi.escape(parser.get(section, option), quote=True))
      print "</div>"
print "</form>"

print "</body></html>"
