#!/usr/bin/env python3
"""HTTPS server for the mixed-form Autofill warning POC.

The page MUST be served over HTTPS so that the form's HTTP action is
treated as mixed content (triggers SuggestionType::kMixedFormMessage,
which renders a single PopupWarningView in the Autofill popup).
"""
import http.server
import os
import ssl
import subprocess
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
CERT = os.path.join(HERE, "server.pem")
PORT = 8443


def ensure_cert():
    if os.path.exists(CERT):
        return
    subprocess.check_call([
        "openssl", "req", "-x509", "-newkey", "rsa:2048",
        "-keyout", CERT, "-out", CERT, "-days", "2", "-nodes",
        "-subj", "/CN=localhost",
    ])


def main():
    ensure_cert()
    os.chdir(HERE)
    httpd = http.server.HTTPServer(("0.0.0.0", PORT),
                                   http.server.SimpleHTTPRequestHandler)
    ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
    ctx.load_cert_chain(CERT)
    httpd.socket = ctx.wrap_socket(httpd.socket, server_side=True)
    sys.stderr.write(f"Serving HTTPS on https://localhost:{PORT}/poc.html\n")
    httpd.serve_forever()


if __name__ == "__main__":
    main()
