#!/bin/bash
# The three agreed stub cases against FROZEN v6 (sha dcfb732a).
#   ./run-v6.sh arm1    early preflight failure -> no product command, no cargo, no state
#   ./run-v6.sh arm2    setup rejection -> request, receipt, census; D1 BEFORE teardown
#   ./run-v6.sh signal  signal -> cleanup once, no trial resumes, cleanup-context wait survives
#
# STUBS ONLY. No cargo, listener, elevation, live probe, product execution, firewall change.
# Real-interpreter passthrough is limited to the driver's own parse of fixture files this rig
# wrote; d1_render and every host probe stay stubbed.
set -u
RIG="$(cd "$(dirname "$0")" && pwd)"
SUBJECT='C:/Users/decid/Documents/projects/spt-core/.spt/preserved/hertz-fp-driver-review/v6-as-delivered/fp-driver-v6.sh'
CASE="${1:?usage: run-v6.sh arm1|arm2|signal}"
export RIGBIN="$RIG/bin"
BOUND=${BOUND:-90}

pass=0; fail=0
check() { if [ "$2" = "$3" ]; then printf '    %-54s PASS\n' "$1"; pass=$((pass+1));
          else printf '    %-54s FAIL (want %s, got %s)\n' "$1" "$2" "$3"; fail=$((fail+1)); fi; }

rm -rf "$RIG/work"; mkdir -p "$RIG/work"
bash "$RIG/make-stubs-v6.sh" > /dev/null
export RIGLOG="$RIG/work"; : > "$RIGLOG/actions.log"

# ---- byte-preserving, config-only copy; body proven unmodified by CONTENT ----
DEST="$RIG/work/v6-$CASE.sh"
sed -b -e "s#^SP='.*'#SP='$RIG/work'#" -e "s#^EXE=\".*\"#EXE=\"$RIG/spt-stub.sh\"#" "$SUBJECT" > "$DEST"
difftxt=$(diff "$SUBJECT" "$DEST"); drc=$?
[ "$drc" -gt 1 ] && { echo "REFUSED: diff instrument failure exit $drc"; exit 9; }
count=$(printf '%s\n' "$difftxt" | grep -c '^[<>]')
[ "$count" -eq 0 ] && { echo "REFUSED: zero changed lines"; exit 9; }
offending=$(printf '%s\n' "$difftxt" | grep '^[<>]' | grep -cvE "^[<>] *(SP=|EXE=)")
[ "$offending" -ne 0 ] && { echo "REFUSED: $offending line(s) outside the config block"; exit 9; }
echo "config-only diff: $count changed lines, 0 outside the config block"
printf '%s\n' "$difftxt" > "$RIG/$CASE-config-only.diff"

FREE=124.00; SPTMODE=arm_a_trial; SIGTAG=''
case "$CASE" in
  arm1)   FREE=1.00; SPTMODE=noop ;;
  arm2)   SPTMODE=arm_a_trial ;;
  signal) SPTMODE=arm_a_trial; SIGTAG=1 ;;   # signal on the FIRST product invocation
esac

echo "=== v6 $CASE — driver starting"
( export PATH="$RIGBIN:$PATH" RIGLOG="$RIG/work" FP_FREE_GIB="$FREE" FP_ELEVATED=False \
         FP_SPT_MODE="$SPTMODE" FP_CENSUS_GROUP=0 FP_CENSUS_29470=0 FP_SIGNAL_ON="$SIGTAG" \
         SPT_DEBUG_RELEASE_SEED=$(printf 'a%.0s' $(seq 64))
  bash -c 'export FP_DRIVER_PID=$$; exec bash "$0"' "$DEST" ) > "$RIG/work/$CASE.out" 2>&1 &
DRIVER=$!

# ---- liam stub: writes the receipt at the path the REQUEST FILE names, with the
# nonce that file carries. Exactly what a correct operator would do.
served=""; waited=0
while [ "$waited" -lt "$BOUND" ]; do
  kill -0 "$DRIVER" 2>/dev/null || { echo "driver exited on its own after ${waited}s"; break; }
  for req in "$RIG"/work/fp-run/*/handoff/*-request.txt; do
    [ -f "$req" ] || continue
    case "$served" in *"$req"*) continue ;; esac
    served="$served $req"
    rf=$(sed -n 's/^receipt_file: //p' "$req" | tr -d '\r')
    nonce=$(sed -n 's/^nonce: //p' "$req" | tr -d '\r')
    name=$(basename "$req")
    runroot=$(dirname "$(dirname "$req")")
    echo "  REQUEST seen: $name  -> receipt_file=$rf  nonce=$nonce"
    case "$name" in
      *setup*)    # the refusal this arm is about
        printf 'ActiveStore enforcement is NotConfigurable; refusing\n' > "$runroot/b-setup.err"
        : > "$runroot/b-setup.out"
        { echo "liam receipt"; echo "nonce: $nonce"; echo "exit=1"; } > "$rf"
        echo "    receipt written: exit=1 (a REFUSED setup)" ;;
      *teardown*) # a clean teardown, so the five-condition verdict can be exercised
        printf 'LAN_FIREWALL_CLEAN\n' > "$runroot/cleanup-teardown.out" 2>/dev/null
        { echo "liam receipt"; echo "nonce: $nonce"; echo "exit=0"; } > "$rf"
        echo "    receipt written: exit=0 (a CLEAN teardown)" ;;
    esac
  done
  sleep 3; waited=$((waited + 3))
done

alive=0; kill -0 "$DRIVER" 2>/dev/null && alive=1
[ "$alive" -eq 1 ] && { echo "  BOUNDED OUT at ${BOUND}s; sending TERM"; kill -TERM "$DRIVER" 2>/dev/null; }
wait "$DRIVER"; rc=$?
cp "$RIG/work/actions.log" "$RIG/$CASE-actions.log"
R=$(ls -d "$RIG"/work/fp-run/*/ 2>/dev/null | head -1)

echo; echo "  --- ordered actions requested:"; cut -c1-150 "$RIG/$CASE-actions.log" | sed 's/^/      /'
echo "  --- driver exit: $rc (alive_at_bound=$alive)"
echo "  --- key findings:"
grep -E 'HANDOFF|D1|TEARDOWN|ARM_B|SIGNAL|CLEANUP_BEGIN|CLEANUP_END|STATE_MARKED|HALT|VOID|GUARD' \
  "$R/findings.txt" 2>/dev/null | cut -c1-170 | sed 's/^/      /'
echo "  --- state markers:"; ls "$R/state" 2>/dev/null | sed 's/^/      /'

spt_calls=$(grep -c '^[0-9]* SPT ' "$RIG/$CASE-actions.log" || true)
cargo_calls=$(grep -c '^[0-9]* CARGO ' "$RIG/$CASE-actions.log" || true)
cleanups=$(grep -c 'CLEANUP_BEGIN' "$R/findings.txt" 2>/dev/null || echo 0)
states=$(ls "$R/state" 2>/dev/null | wc -l)
echo "  --- assertions:"
case "$CASE" in
  arm1)
    check "driver halts nonzero"              1 "$([ "$rc" -ne 0 ] && echo 1 || echo 0)"
    check "NO product command requested"      0 "$spt_calls"
    check "NO cargo requested"                0 "$cargo_calls"
    check "NO resource state marked"          0 "$states"
    check "cleanup entered exactly once"      1 "$cleanups" ;;
  arm2)
    d1_seq=$(grep -n 'D1(setup-rejection)\|D1_FAILED(setup-rejection)' "$R/findings.txt" 2>/dev/null | head -1 | cut -d: -f1)
    td_seq=$(grep -n 'HANDOFF_REQUESTED teardown' "$R/findings.txt" 2>/dev/null | head -1 | cut -d: -f1)
    check "driver exits 3 (Arm B held)"       3 "$rc"
    check "setup non-acceptance recorded"     1 "$(grep -c 'ARM_B_SETUP_NOT_ACCEPTED' "$R/findings.txt" 2>/dev/null || echo 0)"
    check "D1 ran on the rejection"           1 "$([ -n "$d1_seq" ] && echo 1 || echo 0)"
    check "D1 ran BEFORE any teardown request" 1 "$([ -n "$d1_seq" ] && { [ -z "$td_seq" ] || [ "$d1_seq" -lt "$td_seq" ]; } && echo 1 || echo 0)"
    check "cleanup entered exactly once"      1 "$cleanups" ;;
  signal)
    trials_after=$(awk '/SIGNAL/{f=1} f&&/bootstrap/{n++} END{print n+0}' "$R/findings.txt" 2>/dev/null || echo 0)
    check "driver exits 130"                  130 "$rc"
    check "signal recorded"                   1 "$(grep -c 'SIGNAL ' "$R/findings.txt" 2>/dev/null || echo 0)"
    check "cleanup entered exactly once"      1 "$cleanups"
    check "no trial resumed after the signal" 0 "$trials_after" ;;
esac
echo "=== $CASE tally pass=$pass fail=$fail"
