#!/usr/bin/env python3
"""Minimal HTTP server for the POC. Serves www/ on http://localhost:8080."""
import http.server
import os
import socketserver
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
DOCROOT = os.path.join(HERE, 'www')
PORT = 44665


class Handler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory=DOCROOT, **kwargs)

    def end_headers(self):
        # Ensure SW script and pages are never cached so re-runs are deterministic.
        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 ReuseTCPServer(socketserver.TCPServer):
    allow_reuse_address = True


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