#!/usr/bin/python3

import cgi
import html
import json
import os
import urllib.request
import smtplib, ssl


# Config and secrets
smtp_server     = "smtp.example.com"
smtp_port       = 587
smtp_user       = "smtpuser"
smtp_password   = "smtppassword"
from_addr       = "flatfish@example.com"
to_addr         = "staff@example.com"
exapi_newticket = "http://localhost:7001/exapi/newticket"
debug           = False

def dp(s):
    """dp = debug print"""
    if debug:
        print(s)

print("""Content-Type: text/html;charset=utf-8

<html>
<head>
<title>Result of form 1</title>
<link rel="stylesheet" href="../style.css" />
</head>
<body>
""")

form = cgi.FieldStorage()
try:
    f_name=form["name"].value
    f_email=form["email"].value
    f_nightmare=form["nightmare"].value
    f_horrors=form["horrors"].value
    acceptable_nightmares = [ "brokenvpn", "asrocfire", "windows", "lost" ]
    if f_nightmare not in acceptable_nightmares:
        f_nightmare = "unknown";
    dp("<div>You gave your name as “" + html.escape(f_name) + "”</div>")
    dp("<div>You gave your email as “" + html.escape(f_email) + "”</div>")
    dp("<div>You gave your nightmare as “" + html.escape(f_nightmare) + "”</div>")
    dp("<div>You gave your tale of woe as “" + html.escape(f_horrors) + "”</div>")
    dp("<div>Trying to get ticket…")
    taglist = [ "form1a" ]
    propertylist = [ { "key": "nightmare", "value": f_nightmare },
                     { "key": "script",    "value": "post1a" } ]
    payload = { "auth_token": "EXAMPLEAUTHTOKEN",
                "title": "Issue from " + f_name,
                "crule": "exapi1",
                "summary": "Reporting person: " + f_name + "\nEmail address given: " + f_email + "\nTale of woe:\n" + f_horrors + "\n\nHTTP_X_FORWARDED_FOR=" + os.getenv('HTTP_X_FORWARDED_FOR') + "\n" + "REMOTE_ADDR=" + os.getenv('REMOTE_ADDR') + "\n",
                "tags": taglist,
                "properties": propertylist }
    jsonpayload = json.dumps(payload)
    req = urllib.request.Request(exapi_newticket)
    req.add_header('Content-Type', 'application/json; charset=utf-8')
    jsonencoded = jsonpayload.encode('utf-8')
    req.add_header('Content-Length', len(jsonencoded))
    response = urllib.request.urlopen(req, jsonencoded).read()
    responsejson = json.loads(response.decode('utf-8'))
    dp("Got response " + repr(responsejson))
    if "new_number" in responsejson:
        new_num = responsejson["new_number"]
        print("<div class=\"newticket\">Ticket recorded.  Your ticket number is <span id=\"newnum\">" + new_num + "</span></div>")
        print("<div>We could even email or send an SMS from this script if needed…</div>")
        # Email!
        context = ssl.create_default_context()
        try:
            server = smtplib.SMTP(smtp_server, smtp_port)
            server.starttls(context=context) # Secure the connection
            server.login(smtp_user, smtp_password)
            message = "Subject: New ticket\n\nTicket number " + new_num + " issued.\n\nHAND,\nFlatfish server\n"
            server.sendmail(from_addr, to_addr, message)
            print("<div>…email sent to someone running this system.</div>")
        except Exception as ex:
            print("<div class=\"error\">Email problem… aw crap.</div>")
            print("<div class=\"trace\">" + repr(ex) + "</div>")
        finally:
            server.quit() 
    else:
        print("<div class=\"error\">Got a response, but no ticket number.  Something must have gone wrong.</div>")
except Exception as ex:
    print("<div class=\"error\">Well, something went wrong there.  How traumatic.</div>")
    print("<div class=\"trace\">" + repr(ex) + "</div>")

print("""</body>
</html>""")
