#!{{ python_executable }}

import cgi
import cgitb
import json
import os
import subprocess

def refresh():
  command = ["{{ monitor_bin }}", "-a"]
  subprocess.call(command)

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

json_file = "{{ json_file }}"

if not os.path.exists(json_file) or "refresh" in form:
  refresh()

if not os.path.exists(json_file):
  print """<html><head>
  <link rel="stylesheet" href="static/pure-min.css">
  <link rel="stylesheet" href="static/style.css">
  </head><body>
  <h1>Monitoring :</h1>
  No status file found</p></body></html>"""
  exit(0)

result = json.load(open(json_file))

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>Monitoring :</h1>"
print "<form action=\"/index.cgi\" method=\"post\" class=\"pure-form-aligned\">"
print "<input type=\"hidden\" name=\"posting-script\" value=\"{{ pwd }}/{{ this_file }}\">"
print "<p><em>Last time of monitoring process : %s</em></p>" % (result['datetime'])
del result['datetime']
print "<div class=\"pure-controls\"><button type=\"submit\" class=\"pure-button \
 pure-button-primary\" name=\"refresh\" value=\"refresh\">Refresh</button></div></form>"
print "<br/>"

print "<h2>These scripts and promises have failed :</h2>"
for r in result:
  if result[r] != '':
    print "<h3>%s</h3><pre style=\"padding-left:30px;\">%s</pre>" % (cgi.escape(r), cgi.escape(result[r]))
print "<br/>"

print "<h2>These scripts and promises were successful :</h2>"
print "<ul>"
for r in result:
  if result[r] == '':
    print "<li>%s</li>" % (r)
print "</ul>"
print "</body></html>"
