#!/usr/bin/env python3
"""Check the published source files and prepare a locked FFmpeg Docker build context."""

import argparse
import hashlib
import json
import re
import tarfile
import tempfile
from pathlib import Path


def verify_archive(downloads, source, destination=None):
    """Check each download and the whole archive, optionally writing a combined copy."""
    whole_hash = hashlib.sha256()
    total = 0
    for part in source["files"]:
        part_hash = hashlib.sha256()
        size = 0
        part_path = downloads / part["path"]
        with part_path.open("rb") as contents:
            while block := contents.read(1024 * 1024):
                part_hash.update(block)
                whole_hash.update(block)
                if destination is not None:
                    destination.write(block)
                size += len(block)
        if size != part["bytes"] or part_hash.hexdigest() != part["sha256"]:
            raise ValueError(f"Download failed verification: {part['path']}")
        total += size
    if total != source["bytes"] or whole_hash.hexdigest() != source["sha256"]:
        raise ValueError(f"Archive failed verification: {source['filename']}")


def replace_line(text, old_pattern, replacement):
    updated, count = re.subn(old_pattern, lambda match: replacement, text, flags=re.MULTILINE)
    if count != 1:
        raise ValueError(f"Expected one matching line in the release Dockerfile: {old_pattern}")
    return updated


def make_dockerfile(core_archive, sources, toolchain):
    ffmpeg_wasm = sources["ffmpeg-wasm"]
    with tarfile.open(core_archive, "r:gz") as archive:
        original = archive.extractfile(f'{ffmpeg_wasm["archive_root"]}/Dockerfile').read().decode("utf-8")

    parts = {k: v for k, v in sources.items() if v["role"] in {"build", "library", "submodule"}}
    source_stage = ["FROM scratch AS release-sources"]
    for source in parts.values():
        source_stage.append(f'ADD archives/{source["filename"]} /release-sources/')

    # All source inputs are local files, so the release's floating Dockerfile frontend is unnecessary.
    original = replace_line(original, r"^# syntax=.*$", "\n".join(source_stage))
    original = replace_line(
        original, r"^FROM emscripten/emsdk:3\.1\.40 AS emsdk-base$",
        f'FROM {toolchain["docker_image"]} AS emsdk-base',
    )
    original = replace_line(
        original, r"^ARG EXTRA_CFLAGS$",
        "ARG CFLAGS\nARG LDFLAGS\nARG EM_PKG_CONFIG_PATH\nARG PKG_CONFIG_PATH\nARG EXTRA_CFLAGS",
    )
    original = replace_line(original, r"^ENV FFMPEG_LIBS \\$", 'ENV FFMPEG_LIBS="\\')
    original = replace_line(original, r"^      -lzimg$", '      -lzimg"')
    for name, source in sources.items():
        if source["role"] != "library" or name == "zimg":
            continue
        original = replace_line(
            original, rf'^ADD {re.escape(source["repository"])}\.git#\$\w+ /src$',
            f'COPY --from=release-sources /release-sources/{source["archive_root"]}/ /src/',
        )

    zimg = sources["zimg"]["archive_root"]
    googletest = sources["googletest"]["archive_root"]
    original = replace_line(
        original, r"^RUN git clone --recursive -b \$ZIMG_BRANCH https://github\.com/sekrit-twc/zimg\.git /src$",
        f"COPY --from=release-sources /release-sources/{zimg}/ /src/\n"
        f"COPY --from=release-sources /release-sources/{googletest}/ /src/test/extra/googletest/",
    )
    original = replace_line(original, r"^RUN apt-get update && apt-get install -y git$", "")
    original, count = re.subn(
        r"^COPY ((?:build|src)/\S+)(\s+\S+)$",
        lambda m: f'COPY --from=release-sources /release-sources/{ffmpeg_wasm["archive_root"]}/{m[1]}{m[2]}',
        original, flags=re.MULTILINE,
    )
    if count != 19:
        raise ValueError(f"Unexpected number of release recipe inputs: {count}")

    sdl = sources["sdl2"]
    port_cache = (
        "ENV EM_PORTS=/opt/release-ports\n"
        f'COPY archives/{sdl["filename"]} /tmp/release-sdl2.zip\n'
        "RUN python3 -m zipfile -e /tmp/release-sdl2.zip /opt/release-ports/sdl2 \\\n"
        f"    && printf '%s\\n' '{sdl['url']}' > /opt/release-ports/sdl2/.emscripten_url \\\n"
        "    && rm /tmp/release-sdl2.zip\n"
    )
    return replace_line(original, r"^RUN embuilder build sdl2 sdl2-mt$", port_cache + "RUN embuilder build sdl2 sdl2-mt")


def prepare(downloads, target, manifest):
    if target.exists():
        raise ValueError(f"Choose a new output directory: {target}")
    sources = {item["id"]: item for item in manifest["sources"]}
    with tempfile.TemporaryDirectory(prefix="ffmpeg-build-", dir=target.parent) as stage:
        context = Path(stage) / "context"
        archives = context / "archives"
        archives.mkdir(parents=True)
        for source in sources.values():
            if source["role"] == "toolchain":
                verify_archive(downloads, source)
                continue
            with (archives / source["filename"]).open("wb") as assembled:
                verify_archive(downloads, source, assembled)
        core_filename = sources["ffmpeg-wasm"]["filename"]
        dockerfile = make_dockerfile(archives / core_filename, sources, manifest["toolchain"])
        (context / "Dockerfile").write_text(dockerfile, encoding="utf-8", newline="\n")
        context.rename(target)


def main():
    cli = argparse.ArgumentParser(description=__doc__)
    cli.add_argument("--downloads", type=Path, default=Path(__file__).resolve().parent)
    task = cli.add_mutually_exclusive_group(required=True)
    task.add_argument("--verify", action="store_true", help="verify all source files and reconstructed archives")
    task.add_argument("--build-context", type=Path, help="assemble source files into a new Docker context")
    args = cli.parse_args()

    manifest = json.loads((args.downloads / "manifest.json").read_text(encoding="utf-8"))
    if args.verify:
        for source in manifest["sources"]:
            verify_archive(args.downloads, source)
        print(f'Verified {len(manifest["sources"])} original source archives.')
    else:
        target = args.build_context.resolve()
        prepare(args.downloads, target, manifest)
        print(f"Verified source archives and prepared Docker context: {target}")


if __name__ == "__main__":
    main()

