#!/usr/bin/env python3
"""Build the local stock GCC occurrence observer with a scrubbed environment.

The artifact is a development-only GCC plugin. Its ELF dynamic section is
checked before publication: no mutable or relative loader search entries, and
every DT_NEEDED resolves inside the selected compiler's immutable runtime.
"""

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


ROOT = Path(__file__).resolve().parents[1]
SOURCE = ROOT / "experiments/frontend/gcc-observer/Observer.cpp"
STORE = re.compile(r"/nix/store/[0-9a-z]{32}-[A-Za-z0-9+._?=-]+")
ENV_DROP = re.compile(r"^(NIX_|LD_|LIBRARY_PATH$|CPATH$|C_INCLUDE_PATH$|CPLUS_INCLUDE_PATH$|"
                     r"GCC_EXEC_PREFIX$|COMPILER_PATH$|.*FLAGS$|.*_FLAGS$)")


def scrubbed_environment(temp):
    base = {"PATH": "/usr/bin:/bin", "LC_ALL": "C", "TZ": "UTC0", "TMPDIR": str(temp)}
    for key, value in os.environ.items():
        if key not in base and not ENV_DROP.match(key):
            base[key] = value
    return base


def run(argv, env, what, timeout=120):
    result = subprocess.run(argv, env=env, stdin=subprocess.DEVNULL, capture_output=True,
                            text=True, timeout=timeout)
    if result.returncode:
        raise ValueError(f"{what} exited {result.returncode}: {result.stderr[-1200:]}")
    return result


def find_gmp(compiler, env, explicit):
    if explicit:
        header = Path(explicit).resolve(strict=True)
        if header.is_dir():
            header /= "gmp.h"
        if not header.is_file():
            raise ValueError(f"no gmp.h under {explicit}")
        return header.parent
    candidates = sorted(Path("/nix/store").glob("*-gmp-with-cxx-*-dev/include/gmp.h"))
    if not candidates:
        raise ValueError("could not locate a GMP development header; pass --gmp-include")
    digests = set()
    for header in candidates:
        with header.open("rb") as stream:
            digests.add(hashlib.file_digest(stream, "sha256").hexdigest())
    if len(digests) != 1:
        raise ValueError("multiple distinct GMP headers are installed; pass --gmp-include")
    return candidates[0].parent


def dynamic_section(readelf, elf):
    result = subprocess.run([readelf, "-d", str(elf)], capture_output=True, text=True,
                            timeout=30)
    if result.returncode:
        raise ValueError(f"readelf failed for {elf}: {result.stderr[-400:]}")
    needed, runpath, rpath = [], [], []
    for line in result.stdout.splitlines():
        if "(NEEDED)" in line:
            needed.append(line.rsplit("[", 1)[1].rstrip("]"))
        elif "(RUNPATH)" in line:
            runpath.extend(line.split(":", 1)[1].strip().strip("[]").split(":"))
        elif "(RPATH)" in line:
            rpath.extend(line.split(":", 1)[1].strip().strip("[]").split(":"))
    return needed, runpath, rpath


def soname(readelf, library):
    result = subprocess.run([readelf, "-d", str(library)], capture_output=True, text=True,
                            timeout=30)
    match = re.search(r"\(SONAME\).*\[(.+)\]", result.stdout)
    return match.group(1) if match else None


def verify_elf(readelf, artifact, frontend, compiler, env):
    needed, runpath, rpath = dynamic_section(readelf, artifact)
    if rpath:
        raise ValueError(f"rejected RPATH in {artifact}: {rpath}")
    closure = set()
    package = Path(*frontend.parts[:4])
    nix_store = shutil.which("nix-store")
    if nix_store and package.is_dir():
        closure = {Path(p) for p in run([nix_store, "-qR", str(package)], env,
                                        "nix-store query", timeout=60).stdout.splitlines()}
    if not closure:
        raise ValueError("could not establish the selected compiler runtime closure")
    for entry in runpath:
        path = Path(entry)
        match = STORE.match(entry)
        if (not entry or not path.is_absolute() or ".." in path.parts or match is None
                or not path.is_dir()):
            raise ValueError(f"unapproved loader search entry {entry!r}")
        if Path(match.group(0)) not in closure:
            raise ValueError(f"loader search entry outside the compiler runtime: {entry}")
    if not needed:
        raise ValueError("the observer has no dynamic dependencies")
    frontend_runpath = dynamic_section(readelf, frontend)[1]
    search = [*frontend_runpath, *[str(p) for p in sorted(closure) if (p / "lib").is_dir()]]
    for name in needed:
        printed = run([compiler, f"-print-file-name={name}"], env, "compiler search").stdout.strip()
        candidates = [Path(printed)] if printed and printed != name else []
        candidates += [Path(directory) / name for directory in search]
        resolved = None
        for candidate in candidates:
            if not candidate.is_file():
                continue
            actual = candidate.resolve()
            match = STORE.match(str(actual))
            if match is None or Path(match.group(0)) not in closure:
                continue
            if soname(readelf, candidate) == name:
                resolved = actual
                break
        if resolved is None:
            raise ValueError(f"unresolved dynamic dependency {name}")
    return needed, runpath


def plugin_abi(include):
    text = (include / "plugin-version.h").read_text(encoding="utf-8")
    values = dict(re.findall(r"#define\s+GCCPLUGIN_VERSION_(\w+)\s+(\d+)", text))
    return f"{values['MAJOR']}.{values['MINOR']}.{values['PATCHLEVEL']}"


def prepare(args):
    compiler = Path(shutil.which(args.cxx) or "").resolve(strict=True)
    readelf = shutil.which("readelf")
    if not readelf:
        raise ValueError("readelf is required")
    if args.inspect:
        with tempfile.TemporaryDirectory(prefix="vls-gcc-observer-") as temp:
            env = scrubbed_environment(Path(temp))
            frontend = Path(run([compiler, "-print-prog-name=cc1plus"], env,
                                "frontend search").stdout.strip()).resolve(strict=True)
            needed, runpath = verify_elf(readelf, Path(args.inspect).resolve(strict=True),
                                         frontend, compiler, env)
            print(f"needed {', '.join(needed)}")
            print(f"runpath {':'.join(runpath) if runpath else '(none)'}")
        return
    if not args.output:
        raise ValueError("--output is required unless --inspect is used")
    if not SOURCE.is_file():
        raise ValueError(f"missing observer source {SOURCE}")
    output = Path(args.output).absolute()
    output.parent.mkdir(parents=True, exist_ok=True)
    with tempfile.TemporaryDirectory(prefix="vls-gcc-observer-", dir=output.parent) as temp:
        work = Path(temp)
        env = scrubbed_environment(work)
        plugin = Path(run([compiler, "-print-file-name=plugin"], env, "plugin search").stdout.strip())
        include = plugin / "include"
        if not (include / "gcc-plugin.h").is_file():
            raise ValueError(f"no GCC plugin headers under {include}")
        gmp = find_gmp(compiler, env, args.gmp_include)
        version = run([compiler, "-dumpfullversion"], env, "compiler version").stdout.strip()
        target = run([compiler, "-dumpmachine"], env, "compiler target").stdout.strip()
        frontend = Path(run([compiler, "-print-prog-name=cc1plus"], env,
                            "frontend search").stdout.strip()).resolve(strict=True)
        temporary = work / "occurrences.so"
        run([compiler, "-std=c++17", "-fPIC", "-fno-rtti", "-fno-exceptions", "-shared",
             "-I", str(include), "-I", str(gmp), str(SOURCE), "-o", str(temporary)],
            env, "observer build")
        needed, runpath = verify_elf(readelf, temporary, frontend, compiler, env)
        with temporary.open("rb") as stream:
            digest = hashlib.file_digest(stream, "sha256").hexdigest()
        os.chmod(temporary, 0o755)
        os.replace(temporary, output)
        print(f"GCC {version} ({target}) plugin ABI {plugin_abi(include)}")
        print(f"sha256 {digest}")
        print(f"needed {', '.join(needed)}")
        print(f"runpath {':'.join(runpath) if runpath else '(none)'}")
        print(output)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--cxx", default="g++")
    parser.add_argument("--gmp-include", type=Path,
                        help="GMP development include directory (default: verified Nix candidate)")
    parser.add_argument("--output", type=Path,
                        help="published observer artifact (required for a build)")
    parser.add_argument("--inspect", type=Path,
                        help="validate the dynamic section of an existing artifact and exit")
    args = parser.parse_args()
    prepare(args)


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