#!/usr/bin/env python3
"""Minimal HTTP server for the ANGLE foreign-image UAF POC.

Serves poc.html and a tiny generated H.264 MP4 (sample.mp4) on
http://127.0.0.1:8080/.  The MP4 is needed so that Android Chrome takes the
hardware-decode path that produces AHardwareBuffer-backed video frames.
"""
import http.server
import os
import socketserver
import struct
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 8080


def ensure_sample_mp4():
    """Best effort: create sample.mp4 with ffmpeg if available, otherwise
    write a 1x1 placeholder so the page loads (replace with a real H.264 MP4
    on the target device for the AHardwareBuffer path)."""
    out = os.path.join(HERE, "sample.mp4")
    if os.path.exists(out):
        return
    if os.system(
        "ffmpeg -loglevel error -f lavfi -i color=c=red:s=64x64:r=10 "
        "-t 2 -pix_fmt yuv420p -c:v libx264 -profile:v baseline "
        f"-movflags +faststart -y {out}"
    ) == 0:
        return
    # Minimal valid MP4 'ftyp' box so the <video> element doesn't error
    # immediately. Replace with a real hardware-decodable clip on device.
    with open(out, "wb") as f:
        box = b"ftypisom\x00\x00\x02\x00isomiso2avc1mp41"
        f.write(struct.pack(">I", len(box) + 4) + box)


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

    def end_headers(self):
        self.send_header("Cache-Control", "no-store")
        super().end_headers()


if __name__ == "__main__":
    ensure_sample_mp4()
    socketserver.TCPServer.allow_reuse_address = True
    with socketserver.TCPServer(("127.0.0.1", PORT), Handler) as httpd:
        print(f"serving on http://127.0.0.1:{PORT}/poc.html")
        httpd.serve_forever()
