#!/usr/bin/env python3

import sys
import os
import datetime
import http.server
import ssl


PORT   = 8000
HOST   = ""
PUBLIC = "public"
CAMERA = "camera"


class Handler(http.server.SimpleHTTPRequestHandler):

    def __init__(self, *args, **kwargs):
        os.makedirs(CAMERA, exist_ok=True)
        super().__init__(*args, **kwargs, directory=PUBLIC)

    def do_POST(self):
        length = int(self.headers["Content-Length"])
        ext    = str(self.headers["Content-Type"]).split("/")[1]
        base   = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S_%f")
        name   = f"{CAMERA}/{base}.{ext}"
        self.log_message("Receiving '%s'", name)
        with open(name, "wb") as f:
            f.write(self.rfile.read(length))
        self.send_response(200, name)
        self.end_headers()


args = iter(sys.argv[1:])
port = int(next(args, PORT))
host = str(next(args, HOST))

context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain("cert.pem", "key.pem")

httpd = http.server.HTTPServer((host, port), Handler)
httpd.socket = context.wrap_socket(httpd.socket, server_side=True)

httpd.serve_forever()
