#!{{ python_executable }}

import cgi
import cgitb
import ConfigParser
import os
import re
import subprocess

from IPython.lib import passwd

#cgitb.enable(display=0, logdir="/tmp/cgi.log")
cgitb.enable()
form = cgi.FieldStorage()

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("ipython_notebook"):
  parser.add_section("ipython_notebook")

if not parser.has_option("ipython_notebook", "password"):
  parser.set("ipython_notebook", "password", "")

if "password" in form:
  parser.set("ipython_notebook", "password", passwd(form["password"].value))
  # subprocess.call('{{ httpd_graceful }}')
  # TODO: we should restart ipython

with open(config_file, 'w') as file:
  parser.write(file)

# TODO cleanup
print "<html><head>"
print "<link rel=\"stylesheet\" href=\"static/pure-min.css\">"
print "<link rel=\"stylesheet\" href=\"static/style.css\">"
print "</head><body>"
print "<h1>IPython Notebook Password :</h1>"
print "<form action=\"/index.cgi\" method=\"post\" class=\"pure-form-aligned\">"
print "<input type=\"hidden\" name=\"posting-script\" value=\"{{ pwd }}/{{ this_file }}\">"

print """<div class="pure-control-group">
<label for="password">Password*:</label>
<input placeholder="Set your password" type="password" name="password" id="password"></br>
</div><div class="pure-control-group">
<label for="password">Verify Password*:</label>
<input placeholder="Verify password" type="password" name="password_2" id="password_2"></br>
</div><p id="validate-status" style="color:red"></p>
<div class="pure-controls">
<button id="register-button" type="submit" class="pure-button pure-button-primary" disabled>Access</button></div>
</form>
<script type="text/javascript" src="static/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="static/monitor-register.js"></script>
</body></html>
"""

