#!/usr/bin/env python3
"""
Serves the POC files on 0.0.0.0:8080 so the same content is reachable
as both http://localhost:8080/ (top-level embedder) and
http://127.0.0.1:8080/ (cross-origin iframe).

The top-level page additionally sends a
`Permissions-Policy: on-device-speech-recognition=()` header to make the
denial explicit (the PP default of EnableForSelf already denies the
cross-origin iframe even without this header).
"""
import http.server
import os
import socketserver
import sys

PORT = int(os.environ.get('POC_PORT', '8080'))

class Handler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *a, **kw):
        super().__init__(*a, directory=os.path.dirname(os.path.abspath(__file__)), **kw)

    def end_headers(self):
        # Explicitly deny on-device-speech-recognition everywhere via PP
        # header on the top-level response.  (Redundant with the
        # EnableForSelf default for cross-origin iframes, but makes the
        # embedder's intent unambiguous.)
        if self.path.endswith('index.html') or self.path == '/':
            self.send_header('Permissions-Policy',
                             'on-device-speech-recognition=()')
        self.send_header('Cache-Control', 'no-store')
        super().end_headers()

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


class ReusableTCPServer(socketserver.TCPServer):
    allow_reuse_address = True


if __name__ == '__main__':
    with ReusableTCPServer(('0.0.0.0', PORT), Handler) as httpd:
        sys.stderr.write(f"[server] serving on 0.0.0.0:{PORT}\n")
        sys.stderr.write(f"[server] open http://localhost:{PORT}/index.html\n")
        httpd.serve_forever()
