#!/usr/bin/env python3
# Minimal HTTPS server for the POC.
# showSaveFilePicker() requires a secure context; this script generates a
# throwaway self-signed cert and serves the current directory over HTTPS.
import http.server
import os
import ssl
import subprocess
import sys

HOST, PORT = "localhost", 8443
CERT, KEY = "poc-cert.pem", "poc-key.pem"


def ensure_cert():
    if os.path.exists(CERT) and os.path.exists(KEY):
        return
    print("[server] generating throwaway self-signed cert …", file=sys.stderr)
    subprocess.check_call([
        "openssl", "req", "-x509", "-newkey", "rsa:2048",
        "-keyout", KEY, "-out", CERT,
        "-days", "2", "-nodes",
        "-subj", "/CN=localhost",
    ])


def main():
    os.chdir(os.path.dirname(os.path.abspath(__file__)))
    ensure_cert()
    httpd = http.server.HTTPServer((HOST, PORT), http.server.SimpleHTTPRequestHandler)
    ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
    ctx.load_cert_chain(certfile=CERT, keyfile=KEY)
    httpd.socket = ctx.wrap_socket(httpd.socket, server_side=True)
    print(f"[server] serving {os.getcwd()} at https://{HOST}:{PORT}/poc.html",
          file=sys.stderr)
    httpd.serve_forever()


if __name__ == "__main__":
    main()
