#!/usr/bin/env python3
"""Build the opt-in Sulong 24.2.2 entry alloca experiment JAR."""

import argparse
from hashlib import sha256
import os
from pathlib import Path
import re
import shutil
import subprocess
from tempfile import TemporaryDirectory
from zipfile import ZipFile


PATCH = Path(__file__).with_name("sulong-24.2.2-entry-allocas.patch").resolve()
SOURCE_SHA256 = "c9d343fe95227e4257b98e5b2fd0d81f1163a1b6062c3fe5a3d4410813b2414d"
LANGUAGE_SHA256 = "cca48e04504b30aef64b4da92fde24bcdceacc6ed38695a1a10e52e320812e6c"


def require_digest(path, expected):
    if sha256(path.read_bytes()).hexdigest() != expected:
        raise ValueError(f"unexpected SHA-256 for {path}")


def jdk_command(name):
    java_home = os.environ.get("JAVA_HOME")
    return str(Path(java_home, "bin", name)) if java_home else name


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("source_jar", type=Path)
    parser.add_argument("dependency_dir", type=Path)
    parser.add_argument("output_jar", type=Path)
    parser.add_argument("--patch", type=Path, action="append", default=[], help="apply an additional patch after the stack patch")
    args = parser.parse_args()
    source = args.source_jar.resolve(strict=True)
    dependencies = args.dependency_dir.resolve(strict=True)
    language = dependencies / "llvm-language-24.2.2.jar"
    output = args.output_jar.resolve()
    if output == language:
        parser.error("output must use a different path from the stock JAR")

    require_digest(source, SOURCE_SHA256)
    require_digest(language, LANGUAGE_SHA256)
    patches = [PATCH, *[path.resolve(strict=True) for path in args.patch]]
    changed_sources = sorted({entry for patch in patches for entry in
                              re.findall(r"^\+\+\+ b/(.*\.java)$", patch.read_text(), re.MULTILINE)})
    if not changed_sources:
        raise ValueError(f"no Java sources in {PATCH}")

    output.parent.mkdir(parents=True, exist_ok=True)
    with TemporaryDirectory(dir=output.parent) as directory:
        temporary = Path(directory)
        sources = temporary / "src"
        sources.mkdir()
        classes = temporary / "classes"
        classes.mkdir()
        with ZipFile(source) as archive:
            existing = set(archive.namelist())
            for entry in changed_sources:
                if entry in existing:
                    archive.extract(entry, sources)
        for path in patches:
            with path.open("rb") as patch:
                subprocess.run(["patch", "--batch", "--forward", "-p1"], cwd=sources, stdin=patch, check=True)
        subprocess.run([jdk_command("javac"), "-proc:none", "-cp", str(dependencies / "*"),
                        "-d", str(classes), *[str(sources / entry) for entry in changed_sources]], check=True)
        replacement = temporary / "llvm-language.jar"
        shutil.copyfile(language, replacement)
        subprocess.run([jdk_command("jar"), "--update", "--file", str(replacement), "-C", str(classes), "."], check=True)
        replacement.replace(output)
    print(output)


if __name__ == "__main__":
    main()
