#!{{ python_executable }}

import cgi
import cgitb
import ConfigParser
import os

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

print "<html><head>"
print "<link rel=\"stylesheet\" href=\"pure-min.css\">"
print "<link rel=\"stylesheet\" href=\"/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"
  exit(0)

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

for name in form:
  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>"%(option, option)
  print "<input type=\"text\" name=\"%s\" value=\"%s\">"%(option, parser.get('public', option))
  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>"%(option, option)
      print "<input type=\"text\" name=\"%s\" value=\"%s\" readonly>"%(option, parser.get(section, option))
      print "</div>"
print "</form>"

print "</body></html>"