#!/usr/bin/env python3
"""Prepare a local Linux/Nix stock GCC diagnostics profile in the project's dev shell."""

import argparse
import hashlib
import json
import os
from pathlib import Path
import re
import shlex
import shutil
import subprocess
import tempfile


def run(args):
    p = subprocess.run(args, capture_output=True, text=True, timeout=30)
    if p.returncode:
        raise ValueError(f"{Path(args[0]).name} exited {p.returncode}: {p.stderr[-600:]}")
    return p


def store_package(path):
    parts = path.parts
    if (len(parts) < 4 or parts[:3] != ("/", "nix", "store")
            or not re.fullmatch(r"[0-9a-z]{32}-[A-Za-z0-9+._?=-]+", parts[3])):
        raise ValueError(f"expected an immutable Nix store input for {path.name}")
    return Path(*parts[:4])


def executable(name):
    selected = shutil.which(name)
    if not selected:
        raise ValueError(f"could not locate {name}")
    path = Path(selected).resolve(strict=True)
    store_package(path)
    with path.open("rb") as f:
        return {"path": str(path), "sha256": hashlib.file_digest(f, "sha256").hexdigest()}


def plan(command):
    lines = run(command).stderr.splitlines()
    stages = [shlex.split(line) for line in lines if line.lstrip().startswith(("/", '"/'))]
    if len(stages) != 1 or Path(stages[0][0]).name != "cc1plus":
        raise ValueError("expected exactly one GCC C++ frontend in the driver dry run")
    return stages[0]


def prepare(cxx, observer=None):
    driver, bwrap, tracer, limiter = (executable(name) for name in (cxx, "bwrap", "strace", "prlimit"))
    version = run([driver["path"], "-dumpfullversion"]).stdout.strip()
    target = run([driver["path"], "-dumpmachine"]).stdout.strip()
    if version != "16.2.0" or not re.fullmatch(r"[a-zA-Z0-9_-]{1,128}", target):
        raise ValueError("the verified profile requires GCC 16.2.0 with a known target")
    probe = ["-###", "-fsyntax-only", "-fdiagnostics-format=sarif-stderr",
             "-frandom-seed=vls-probe", "-std=c++26", "-freflection", "/vls-check/sample.cpp"]
    reference = plan([driver["path"], *probe])
    frontend = executable(reference[0])
    roots = {store_package(Path(x["path"])) for x in (driver, frontend, tracer)}
    system = {Path(reference[i + 1]) for i, word in enumerate(reference[:-1])
              if word in ("-isystem", "-idirafter", "-I")}
    for path in system:
        store_package(path)
        if not path.is_dir():
            raise ValueError("the compiler reported a missing system include directory")
    closure = set(run(["nix-store", "-qR", *sorted(roots)]).stdout.splitlines())
    if not 0 < len(closure) <= 128 or any(store_package(Path(p)) != Path(p) for p in closure):
        raise ValueError("unexpected tool runtime closure")
    mounts = sorted(closure | {str(p) for p in system if str(store_package(p)) not in closure})
    key = "NIX_CFLAGS_COMPILE_" + target.replace("-", "_")
    # Reproduce the cc-wrapper's target-specific include/seed settings with a closed environment.
    words = shlex.split(os.environ.get(key, os.environ.get("NIX_CFLAGS_COMPILE", "")))
    i = 0
    while i < len(words):
        if re.fullmatch(r"-frandom-seed=[A-Za-z0-9._-]+", words[i]):
            i += 1
        elif i + 1 < len(words) and words[i] in ("-isystem", "-idirafter", "-I"):
            p = Path(words[i + 1])
            store_package(p)
            if p not in system or not re.fullmatch(r"/[A-Za-z0-9_+./=-]+", str(p)):
                raise ValueError("unverified toolchain include option")
            i += 2
        else:
            raise ValueError("the toolchain includes an unsupported environment flag")
    sandbox = [bwrap["path"], "--unshare-all", "--die-with-parent", "--new-session",
               "--clearenv", "--setenv", "LC_ALL", "C", "--setenv", "TZ", "UTC0",
               "--setenv", "TZDIR", str(Path(frontend["path"]).parent),
               "--dev", "/dev", "--tmpfs", "/tmp"]
    for mount in mounts:
        sandbox += ["--ro-bind", mount, mount]
    sandbox += ["--setenv", key, " ".join(words), "--dir", "/vls-check", "--chdir", "/vls-check", "--"]
    for flags in (probe, [*probe, "-DPROFILE_CHECK=1", "-pthread", "-O2", "-fPIC"]):
        if plan([driver["path"], *flags]) != plan([*sandbox, driver["path"], *flags]):
            raise ValueError("isolated compiler options differ from the selected dev shell")
    data = {"schema": 1, "version": version, "target": target, "driver": driver,
            "frontend": frontend, "bubblewrap": bwrap, "strace": tracer, "prlimit": limiter, "mounts": mounts,
            "toolchainFlags": words}
    if observer is not None:
        path = Path(observer).resolve(strict=True)
        if not path.is_absolute() or not path.is_file():
            raise ValueError("--observer must be an absolute regular artifact")
        with path.open("rb") as binary:
            data["observer"] = {"path": str(path), "sha256": hashlib.file_digest(binary, "sha256").hexdigest()}
    return data


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--cxx", default="g++")
    parser.add_argument("--observer", type=Path,
                        help="absolute stock occurrence observer artifact to select")
    parser.add_argument("--output", type=Path, default=Path("build/gcc-profile.json"))
    args = parser.parse_args()
    data = prepare(args.cxx, args.observer)
    output = args.output.absolute()
    output.parent.mkdir(parents=True, exist_ok=True)
    with tempfile.NamedTemporaryFile(mode="w", dir=output.parent, delete=False) as f:
        try:
            json.dump(data, f, indent=2)
            f.write("\n")
            f.flush()
            os.fsync(f.fileno())
            os.replace(f.name, output)
        finally:
            Path(f.name).unlink(missing_ok=True)
    print(f"GCC {data['version']} ({data['target']}), verified {len(data['mounts'])} mounts. {output}")


if __name__ == "__main__":
    try:
        main()
    except (OSError, ValueError, subprocess.SubprocessError) as exc:
        raise SystemExit(f"prepare-gcc-profile: {exc}")
