#!/usr/bin/env python3
"""`repro --each --coverage DIR ...` for Swift: a profiling build of the harness (no sanitizer
coverage), the programs run by the reproducer driver (one child per program, counters flushed on
exit, crash or timeout), then llvm-profdata + llvm-cov: DIR/lcov.info, DIR/html/, DIR/report.txt.
Only package sources are measured (the harness and the library, not the Stitch package).
"""
import glob
import os
import subprocess
import sys
from pathlib import Path


def main():
    here = Path(sys.argv[1])
    args = sys.argv[2:]
    i = args.index("--coverage")
    covdir = Path(args[i + 1]).resolve()
    rest = args[:i] + args[i + 2:]
    covdir.mkdir(parents=True, exist_ok=True)
    build = Path("/tmp/stitch-swift-cov")
    r = subprocess.run(["stitch-build", "--coverage", "--out", str(build), "--project", os.getcwd(), "--json"],
                       capture_output=True, text=True)
    if r.returncode != 0:
        sys.stderr.write(r.stdout[-4000:] + r.stderr[-4000:])
        return 1
    worker = build / "app" / "worker"
    prof = covdir / "profraw"
    prof.mkdir(exist_ok=True)
    env = dict(os.environ, LLVM_PROFILE_FILE=str(prof / "%p.profraw"))
    env.pop("STITCH_SWIFT_ENGINE", None)
    r = subprocess.run([str(worker), *rest], env=env)
    raws = glob.glob(str(prof / "*.profraw"))
    if not raws:
        sys.stderr.write("[stitch] no coverage data written\n")
        return 1
    data = covdir / "merged.profdata"
    subprocess.run(["llvm-profdata", "merge", "-sparse", "-o", str(data), *raws], check=True)
    ignore = ["-ignore-filename-regex=(/stitch/swift/Stitch/|/\\.build/checkouts/swift-|/usr/)"]
    with open(covdir / "lcov.info", "w") as f:
        subprocess.run(["llvm-cov", "export", "-format=lcov", str(worker), "-instr-profile", str(data), *ignore], stdout=f, check=True)
    with open(covdir / "report.txt", "w") as f:
        subprocess.run(["llvm-cov", "report", str(worker), "-instr-profile", str(data), *ignore], stdout=f)
    subprocess.run(["llvm-cov", "show", str(worker), "-instr-profile", str(data), "-format=html",
                    "-output-dir", str(covdir / "html"), *ignore], stdout=subprocess.DEVNULL)
    for p in raws:
        os.unlink(p)
    return r.returncode


if __name__ == "__main__":
    sys.exit(main())
