#!/usr/bin/python3 -u
# autopkgtest check: The service runs and seeds urandom,
# validating the apparmor profile.

import hashlib
import subprocess
from multiprocessing import Process
from pathlib import Path
from http.server import HTTPServer, BaseHTTPRequestHandler


class MockPollen(BaseHTTPRequestHandler):
    def log_request(self, *_a, **_kw):
        pass

    def do_POST(self):
        payload = self.rfile.read(int(self.headers["Content-Length"]))
        _, _, challenge = payload.strip().partition(b"=")
        hasher = hashlib.sha512()
        hasher.update(challenge)
        hash = hasher.hexdigest()
        result = "{0}\n{0}\n".format(hash).encode()
        self.send_response(200)
        self.send_header("Content-Length", str(len(result)))
        self.end_headers()
        self.wfile.write(result)


print("spawning mock server")
subproc = Process(target=HTTPServer(("localhost", 8080), MockPollen).serve_forever)
subproc.start()

SEEDED = Path("/var/cache/pollinate/seeded")
SEEDED.unlink(True)
try:
    print("Running pollinate")
    proc = subprocess.Popen(
        ["sudo", "-u", "pollinate", "--", "pollinate", "-s", "http://localhost:8080/"],
        stderr=subprocess.STDOUT,
    )
    assert proc.wait() == 0
    print("Checking for", SEEDED)
finally:
    subproc.kill()

if not SEEDED.exists():
    print("seeded marker file missing")
    exit(1)

print("run: OK")
