#!/bin/sh
# Dry run for the Prop AMM Network: score a rebuild on your own computer against the exact
# cases the judge replays, for free, as many times as you want.
#   curl -fsSL https://www.propammnetwork.xyz/verifier/dryrun.sh | sh -s <program> <crate dir | file.so>
# Needs: curl, tar, a Rust toolchain (cargo) and, for a crate directory, Agave cargo build-sbf.
# It downloads the dry run info, the original ELF and the corpus by hash (and checks the hashes),
# builds the replayer from the served source once (cached in ~/.cache/propamm), builds your crate
# the way the judge does (cargo build-sbf -- --locked), replays every real case plus the fuzzed
# variants with the judge's seed and prints a summary. It only downloads: nothing is uploaded.
set -eu
SITE="${PROPNET_SITE:-https://www.propammnetwork.xyz}"
SITE="${SITE%/}"
USAGE="curl -fsSL ${SITE:-https://<site>}/verifier/dryrun.sh | sh -s <program> <crate dir | file.so>"
if [ $# -lt 2 ]; then echo "usage: $USAGE" >&2; exit 2; fi
[ -n "$SITE" ] || { echo "set the site: PROPNET_SITE=https://<site> sh dryrun.sh <program> <crate dir | file.so>" >&2; exit 2; }
PROGRAM="$1"; INPUT="$2"
CACHE="${PROPNET_CACHE:-${XDG_CACHE_HOME:-$HOME/.cache}/propamm}"
T0=$(date +%s)

die() { echo "dry run stopped: $*" >&2; exit 2; }
step() { printf '[%4ss] %s\n' "$(( $(date +%s) - T0 ))" "$*"; }
row() { printf '  %-20s %s\n' "$1" "$2"; }
sha() { if command -v sha256sum >/dev/null 2>&1; then sha256sum "$1" | cut -d' ' -f1; else shasum -a 256 "$1" | cut -d' ' -f1; fi; }
disp() { case "$1" in "$HOME"/*) echo "~${1#"$HOME"}" ;; *) echo "$1" ;; esac; }
cut160() { awk '{ if (length($0) > 160) print substr($0, 1, 157) "..."; else print }'; }

for c in curl tar cargo awk sed; do command -v "$c" >/dev/null 2>&1 || die "$c not found (a dry run needs curl, tar and a Rust toolchain with cargo)"; done
case "$INPUT" in /*) ABS="$INPUT" ;; *) ABS="$(pwd)/$INPUT" ;; esac
if [ -d "$ABS" ]; then
  [ -f "$ABS/Cargo.toml" ] || die "$INPUT has no Cargo.toml"
  MODE=crate
elif [ -f "$ABS" ]; then
  MODE=binary
else
  die "$INPUT not found"
fi

mkdir -p "$CACHE/reports"
W="$(mktemp -d "${TMPDIR:-/tmp}/propamm-dryrun.XXXXXX")"
trap 'rm -rf "$W"' EXIT INT TERM

echo "Prop AMM Network, dry run"
echo "Downloads only. Your crate and your binary never leave this computer."
echo

# 1. what the judge replays for this program
step "reading the dry run info for $PROGRAM"
code="$(curl -sS -o "$W/info.json" -w '%{http_code}' "$SITE/api/v1/dryrun/$PROGRAM")" || die "could not reach $SITE"
if [ "$code" != "200" ]; then cat "$W/info.json" >&2; exit 2; fi
field() { sed -n "s/.*\"$1\":\"\{0,1\}\([^\",}]*\).*/\1/p" "$W/info.json" | head -1; }
LABEL="$(field label)"; OURL="$(field original_url)"; OSHA="$(field original_sha256)"
CURL_="$(field corpus_url)"; CSHA="$(field corpus_sha256)"; CASES="$(field cases)"; FUZZ="$(field fuzz)"
SLOT="$(field slot)"; DATE="$(field date)"; AGAVE="$(field agave)"; TOOLS="$(field platform_tools)"
[ -n "$OSHA" ] && [ -n "$CSHA" ] && [ -n "$FUZZ" ] || die "unexpected dry run info from $SITE"

# 2. the replayer, built once from the served source and cached by the hash of that source
step "fetching the replayer source"
curl -fsSL "$SITE/verifier/replayer-src.tar.gz" -o "$W/replayer-src.tar.gz"
mkdir "$W/src"
tar -xzf "$W/replayer-src.tar.gz" -C "$W/src"
(cd "$W/src" && find replayer -type f | LC_ALL=C sort | while IFS= read -r f; do echo "$(sha "$f")  $f"; done) > "$W/src.list"
RSHA="$(sha "$W/src.list" | cut -c1-16)"
R="$CACHE/replayer-$RSHA"
if [ -x "$R" ]; then
  step "replayer cached: $(disp "$R")"
else
  step "building the replayer once (cargo build --release --locked, a few minutes the first time)"
  (cd "$W/src/replayer" && CARGO_TARGET_DIR="$CACHE/target" cargo build --release --locked -q) || die "the replayer did not build"
  cp "$CACHE/target/release/replayer" "$R.part" && mv "$R.part" "$R"
  step "replayer built: $(disp "$R")"
fi

# 3. the original ELF and the corpus, by hash
ORIG="$CACHE/original-$OSHA.so"
if [ -f "$ORIG" ]; then
  step "original ELF cached, sha256 $OSHA"
else
  step "downloading the original ELF"
  curl -fsSL "$OURL" -o "$W/original.so"
  got="$("$R" hash "$W/original.so")"
  [ "$got" = "$OSHA" ] || die "the original ELF hashes to $got, expected $OSHA"
  mv "$W/original.so" "$ORIG"
  step "original ELF sha256 $OSHA checked"
fi
CORP="$CACHE/corpus-$CSHA.json"
if [ -f "$CORP" ]; then
  step "corpus cached, sha256 $CSHA"
else
  step "downloading the corpus"
  curl -fsSL "$CURL_" -o "$W/corpus.json"
  got="$(sha "$W/corpus.json")"
  [ "$got" = "$CSHA" ] || die "the corpus hashes to $got, expected $CSHA"
  mv "$W/corpus.json" "$CORP"
  step "corpus sha256 $CSHA checked"
fi

# 4. the candidate: built like the judge builds it, or the .so you gave
LOCAL=""
if [ "$MODE" = crate ]; then
  LOCAL="$( { cargo-build-sbf --version 2>/dev/null || cargo build-sbf --version 2>/dev/null || true; } | head -1 | awk '{print $2}')"
  [ -n "$LOCAL" ] || die "cargo build-sbf not found: install Agave $AGAVE, the version the judge builds with"
  if [ "$LOCAL" != "$AGAVE" ]; then
    echo "warning: your cargo build-sbf is Agave $LOCAL; the judge builds with Agave $AGAVE (platform tools $TOOLS)."
    echo "         Another compiler can change log lines and compute use, so this dry run may not match the judge."
  fi
  step "building $INPUT with cargo build-sbf -- --locked (Agave $LOCAL)"
  (cd "$ABS" && cargo build-sbf -- --locked) > "$W/build.log" 2>&1 || { tail -n 40 "$W/build.log" >&2; die "the crate did not build"; }
  SO="$(ls -t "$ABS"/target/deploy/*.so 2>/dev/null | head -1 || true)"
  [ -n "$SO" ] || die "no .so in $INPUT/target/deploy after the build; pass the .so path instead"
  step "built $(basename "$SO")"
else
  SO="$ABS"
fi
CAND_SHA="$("$R" hash "$SO")"
REPORT="$CACHE/reports/$PROGRAM-$(echo "$CAND_SHA" | cut -c1-16).json"

# 5. the same replay as the judge: same corpus, same fuzz count, seed derived from the corpus sha256
step "replaying $CASES real cases and $FUZZ fuzzed variants"
"$R" replay --original "$ORIG" --candidate "$SO" --corpus "$CORP" --fuzz "$FUZZ" --out "$REPORT" > "$W/replay.out" || die "the replay did not finish"
step "replay done"

num() { sed -n "s/^  \"$1\": \([0-9a-z]*\),\{0,1\}$/\1/p" "$REPORT" | head -1; }
TOTAL="$(num cases_total)"; COMPARED="$(num compared)"; BUDGET="$(num budget_bound)"; MATCHED="$(num matched)"
RT="$(num real_total)"; RM="$(num real_matched)"; FT="$(num fuzz_total)"; FM="$(num fuzz_matched)"
OK="$(num ok_path_original)"; OKMIN="$(num ok_path_minimum)"; MISS="$(num mismatches_total)"
ELFOK="$(num corpus_elf_sha256_matches_original)"

echo
echo "Summary"
row "target" "$LABEL"
row "program" "$PROGRAM"
row "snapshot" "slot $SLOT, $DATE"
row "original sha256" "$OSHA"
row "corpus sha256" "$CSHA"
row "candidate sha256" "$CAND_SHA"
if [ "$MODE" = crate ]; then row "candidate" "$INPUT, built here with Agave $LOCAL"; else row "candidate" "$INPUT (binary as given)"; fi
row "judge build" "Agave $AGAVE, platform tools $TOOLS, cargo build-sbf -- --locked"
echo
printf '  %-20s %8s\n' "cases" "$TOTAL"
printf '  %-20s %8s   %s\n' "budget_bound" "$BUDGET" "original ran out of compute units, not compared"
printf '  %-20s %8s\n' "compared" "$COMPARED"
printf '  %-20s %8s\n' "matched" "$MATCHED"
printf '  %-20s %8s   %s\n' "  real" "$RM" "of $RT"
printf '  %-20s %8s   %s\n' "  fuzzed" "$FM" "of $FT"
printf '  %-20s %8s   %s\n' "original succeeds" "$OK" "at least $OKMIN needed"
printf '  %-20s %8s\n' "differing cases" "$MISS"

if [ "${MISS:-0}" != "0" ]; then
  echo
  echo "First difference"
  awk '
    function val(s) { sub(/^ *"[a-z_]+": "/, "", s); sub(/",?$/, "", s); return s }
    /^ *"case": "/ { n++; if (n > 1) exit; print "  case       " val($0); next }
    n == 1 && /^ *"kind": "/ { print "  kind       " val($0); next }
    n == 1 && /^ *"data": "/ { d = val($0); if (length(d) > 96) d = substr(d, 1, 93) "..."; print "  data       " d " (base64)"; next }
    n == 1 && /^ *"field": "/ { k++; if (k > 4) exit; print ""; print "  differs    " val($0); next }
    n == 1 && k <= 4 && /^ *"original": "/ { print "  original   " val($0); next }
    n == 1 && k <= 4 && /^ *"candidate": "/ { print "  candidate  " val($0); next }
  ' "$REPORT" | sed 's/\\"/"/g; s/\\\\/\\/g' | cut160
fi

echo
row "full report" "$(disp "$REPORT")"
row "took" "$(( $(date +%s) - T0 ))s"
echo
if [ "$ELFOK" = "false" ]; then
  echo "not yet: the original ELF does not match the corpus snapshot (download again)"
  exit 1
elif [ "${MISS:-1}" = "0" ] && [ "${OK:-0}" -ge "${OKMIN:-100}" ]; then
  echo "PASS-ready: every compared case matches"
  exit 0
elif [ "${MISS:-1}" = "0" ]; then
  echo "not yet: every compared case matches, but only $OK cases succeed on the original ($OKMIN needed)"
  exit 1
else
  echo "not yet: $MATCHED of $COMPARED match"
  exit 1
fi
