#!/usr/bin/env python3
"""HTTPS server for the Protected Audience NaN-priority POC.

Serves poc.html, bidding.js, decision.js, ad.html with the headers
required by the Protected Audience API. Generates a self-signed cert
on first run.
"""
import http.server
import os
import ssl
import subprocess
import sys

PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 8443
DIR = os.path.dirname(os.path.abspath(__file__))
CERT = os.path.join(DIR, 'server.pem')

if not os.path.exists(CERT):
    subprocess.check_call([
        'openssl', 'req', '-x509', '-newkey', 'rsa:2048',
        '-keyout', CERT, '-out', CERT, '-days', '365', '-nodes',
        '-subj', '/CN=localhost',
        '-addext', 'subjectAltName=DNS:localhost,DNS:a.test',
    ])

class Handler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *a, **kw):
        super().__init__(*a, directory=DIR, **kw)

    def end_headers(self):
        # Required so the bidding/decision worklets are allowed to load.
        self.send_header('Ad-Auction-Allowed', 'true')
        self.send_header('X-Allow-FLEDGE', 'true')
        self.send_header('Supports-Loading-Mode', 'fenced-frame')
        self.send_header('Permissions-Policy',
                         'join-ad-interest-group=*, run-ad-auction=*')
        super().end_headers()

    def guess_type(self, path):
        if path.endswith('.js'):
            return 'application/javascript'
        return super().guess_type(path)

    def log_message(self, fmt, *args):
        sys.stderr.write('[server] ' + (fmt % args) + '\n')


http.server.ThreadingHTTPServer.allow_reuse_address = True
httpd = http.server.ThreadingHTTPServer(('0.0.0.0', PORT), Handler)
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ctx.load_cert_chain(CERT)
httpd.socket = ctx.wrap_socket(httpd.socket, server_side=True)
print(f'Serving HTTPS on https://localhost:{PORT}/', flush=True)
httpd.serve_forever()
