#!/usr/bin/env python3
"""Build a STITCH++ Rust harness inside the project image.

harness/*.rs become modules of the crate `stitch_harness` in <out>/app/crate, with `stitch` and
stitch.toml [rust.dependencies] as dependencies. Writes
  <out>/app/worker      fuzzer (loads the engine library: in-process, fork server), worker of the
                        pipe protocol (STITCH_RUST_PIPE=1), and reproducer (SanitizerCoverage, ASan)
  <out>/fuzzer, <out>/repro, <out>/manifest.json
stitch.toml [rust]: dependencies = { mylib = { path = "/src" } }
                    sanitizers = ["address"]        ([] on targets without ASan)
                    overflow_checks = true
"""
import argparse
import json
import os
import re
import shutil
import subprocess
import sys
import tomllib
from pathlib import Path

# endpoint! { [comments] [#[attrs]] [pub] fn NAME
STUB_RE = re.compile(r"endpoint!\s*\{(?:\s*(?://[^\n]*|#\[[^\]]*\]))*\s*(?:pub(?:\([^)]*\))?\s+)?fn\s+(\w+)")
DECODER_RE = re.compile(r"decoder!\s*\(\s*\w+\s*,\s*fn\s+(\w+)")


def strip_comments(text):
    """Remove /* */ blocks and whole-line // comments, so commented-out stubs (like the example in
    the `stitch init` template) are not registered."""
    text = re.sub(r"/\*.*?\*/", lambda m: "\n" * m.group(0).count("\n"), text, flags=re.S)
    return re.sub(r"(?m)^[ \t]*//.*$", "", text)


def toml_value(v):
    if isinstance(v, bool):
        return "true" if v else "false"
    if isinstance(v, (int, float)):
        return str(v)
    if isinstance(v, str):
        return json.dumps(v)
    if isinstance(v, list):
        return "[" + ", ".join(toml_value(x) for x in v) + "]"
    if isinstance(v, dict):
        return "{ " + ", ".join(f"{k} = {toml_value(x)}" for k, x in v.items()) + " }"
    raise ValueError(v)


def host():
    out = subprocess.run(["rustc", "-vV"], capture_output=True, text=True).stdout
    return re.search(r"host: (\S+)", out).group(1)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--project", default="/project")
    ap.add_argument("--out", default=None)
    ap.add_argument("--target", default="all")
    ap.add_argument("--json", action="store_true")
    a = ap.parse_args()
    proj = Path(a.project).resolve()
    cfg = tomllib.loads((proj / "stitch.toml").read_text()) if (proj / "stitch.toml").exists() else {}
    rs = cfg.get("rust", {})
    out = Path(a.out) if a.out else proj / ".stitch" / "build"
    if not out.is_absolute():
        out = proj / out
    out.mkdir(parents=True, exist_ok=True)
    app = out / "app"
    crate = app / "crate"
    shutil.rmtree(app, ignore_errors=True)
    (crate / "src" / "bin").mkdir(parents=True)
    srcs = sorted(p for p in (proj / "harness").glob("*.rs"))
    if not srcs:
        return finish(a, {"ok": False, "errors": [{"file": "harness", "output": "no harness/*.rs files"}]})
    mods, regs = [], []
    for p in srcs:
        m = p.stem
        shutil.copy2(p, crate / "src" / p.name)
        mods.append(m)
        text = strip_comments(p.read_text())
        regs += [f"    {m}::{s}::__stitch_register();" for s in DECODER_RE.findall(text) + STUB_RE.findall(text)]
    (crate / "src" / "lib.rs").write_text(
        "#![allow(unused_imports, dead_code, unused_mut, non_snake_case)]\n"
        + "".join(f"pub mod {m};\n" for m in mods)
        + "\n/// Registers every stub and decoder (generated by stitch-build).\npub fn __stitch_register() {\n"
        + "\n".join(regs) + "\n}\n")
    (crate / "src" / "bin" / "worker.rs").write_text(
        "fn main() {\n    stitch_harness::__stitch_register();\n    stitch::main();\n}\n")
    # in-process fuzzing: the engine library (dlopen'ed) calls the stitch_* ABI of the binary
    (crate / "build.rs").write_text(
        'fn main() {\n    println!("cargo:rustc-link-arg-bin=worker=-Wl,--export-dynamic-symbol=stitch_*");\n}\n')
    deps = "".join(f"{k} = {toml_value(v)}\n" for k, v in rs.get("dependencies", {}).items())
    overflow = "true" if rs.get("overflow_checks", True) else "false"
    (crate / "Cargo.toml").write_text(f"""[package]
name = "stitch_harness"
version = "0.0.0"
edition = "2021"

build = "build.rs"

[lib]
path = "src/lib.rs"

[[bin]]
name = "worker"
path = "src/bin/worker.rs"

[dependencies]
stitch = {{ path = "/stitch/rust/stitch" }}
{deps}
[profile.release]
debug = "limited"
debug-assertions = true
overflow-checks = {overflow}
panic = "unwind"
opt-level = 2
codegen-units = 1  # SanitizerCoverage + several codegen units can leave hidden symbols undefined

[workspace]
""")
    if (proj / "harness" / "Cargo.lock").exists():
        shutil.copy2(proj / "harness" / "Cargo.lock", crate / "Cargo.lock")
    triple = host()
    san = rs.get("sanitizers", cfg.get("build", {}).get("sanitizers", ["address"]))
    # every crate emits its own generic instantiations: crates are instrumented differently
    rustflags = " ".join(["-Zshare-generics=n"] + (["-Zsanitizer=address"] if "address" in san else []))
    env = dict(os.environ, CARGO_HOME=str(proj / ".stitch" / "cargo"), RUSTC_WRAPPER="/stitch/bin/stitch-rustc",
               STITCH_SANCOV="1", RUSTFLAGS=rustflags, CARGO_TARGET_DIR=str(proj / ".stitch" / "cargo-target" / "fuzz"))
    r = subprocess.run(["cargo", "build", "--release", "--target", triple, "--bin", "worker"], cwd=crate, env=env,
                       capture_output=True, text=True)
    if r.returncode != 0:
        errs = "\n".join(l for l in r.stderr.splitlines() if not l.strip().startswith(("Compiling", "Downloaded", "Downloading", "Updating", "Locking", "Adding")))
        return finish(a, {"ok": False, "errors": [{"file": "cargo build", "output": errs[-8000:]}]})
    shutil.copy2(Path(env["CARGO_TARGET_DIR"]) / triple / "release" / "worker", app / "worker")
    if (crate / "Cargo.lock").exists():
        shutil.copy2(crate / "Cargo.lock", app / "Cargo.lock")
    head = ["#!/bin/sh", 'HERE="$(cd "$(dirname "$0")" && pwd)"',
            "export ASAN_OPTIONS=${ASAN_OPTIONS:-abort_on_error=1:detect_leaks=0:symbolize=1:allocator_may_return_null=1:handle_abort=1:detect_stack_use_after_return=0}",
            f"export STITCH_RUSTFLAGS_SAN={rustflags!r}"]
    # in-process (default): the worker binary loads the engine library and runs it in its own
    # process (fork server, shared memory). STITCH_RUST_PIPE=1: the pipe protocol instead.
    (out / "fuzzer").write_text("\n".join(head + [
        'if [ -n "$STITCH_RUST_PIPE" ] || [ ! -f /stitch/lib/libstitch_engine.so ]; then',
        '  export STITCH_WORKER="\'$HERE/app/worker\' worker"', '  exec /stitch/bin/stitch-engine "$@"', 'fi',
        'export STITCH_NATIVE_ENGINE=1', 'exec "$HERE/app/worker" "$@"', ""]))
    (out / "repro").write_text("\n".join(head + [
        'case " $* " in *" --coverage "*) exec /stitch/bin/stitch-rust-cov "$HERE/app" "$@";; esac',
        'exec "$HERE/app/worker" "$@"', ""]))
    for f in ("fuzzer", "repro"):
        (out / f).chmod(0o755)
    r = subprocess.run([str(out / "repro"), "--manifest"], capture_output=True, text=True, cwd=proj)
    if r.returncode != 0 or not r.stdout.strip():
        return finish(a, {"ok": False, "errors": [{"file": "harness", "output": (r.stderr or r.stdout)[-8000:]}]})
    m = json.loads(r.stdout.strip().splitlines()[-1])
    (out / "manifest.json").write_text(json.dumps(m))
    return finish(a, {"ok": True, "endpoints": len(m["endpoints"]), "objects": len(m["objects"]),
                      "datatypes": len(m["datatypes"]), "errors": []})


def finish(a, res):
    if a.json:
        print(json.dumps(res))
    elif res["ok"]:
        print(f"built: {res['endpoints']} endpoints, {res['objects']} object types, {res['datatypes']} datatypes")
    else:
        for e in res["errors"]:
            sys.stderr.write(e["output"] + "\n")
    sys.exit(0 if res["ok"] else 1)


if __name__ == "__main__":
    main()
