#!/bin/bash
# ARM 2 against fp-driver-v5.sh — SETUP REJECTION.
# Ordering to assert (todlando): request -> receipt -> census, with D1 BEFORE any
# teardown request, and the census deciding when it disagrees with the receipt.
# STUBS ONLY. No cargo, listener, elevation, live probe or firewall change.
#
# The liam stub is a WATCHER: it reads the driver's own request file and writes
# the receipt at the path that file names, with the nonce that file carries --
# i.e. it does exactly what a correct human operator would do. If the driver then
# fails to see it, the failure is the driver's extraction, not the receipt.
set -u
RIG="$(cd "$(dirname "$0")" && pwd)"
SUBJECT='C:/Users/decid/Documents/projects/spt-core/.spt/preserved/hertz-fp-driver-review/v5-as-delivered/fp-driver-v5.sh'
export RIGBIN="$RIG/bin"
BOUND=${BOUND:-75}          # seconds of observation before the arm is bounded out

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

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

echo "=== ARM 2 (v5 6f409f91) — driver started; liam-stub watcher armed"
( export PATH="$RIGBIN:$PATH" RIGLOG="$RIG/work" FP_FREE_GIB=124.00 FP_ELEVATED=False \
         FP_SPT_MODE=arm_a_trial FP_CENSUS_GROUP=0 FP_CENSUS_29470=0 \
         SPT_DEBUG_RELEASE_SEED=$(printf 'a%.0s' $(seq 64))
  bash "$RIG/work/v5-arm2.sh" ) > "$RIG/work/arm2.out" 2>&1 &
DRIVER=$!

served=0; waited=0
while [ "$waited" -lt "$BOUND" ]; do
  kill -0 "$DRIVER" 2>/dev/null || { echo "driver exited on its own after ${waited}s"; break; }
  req=$(ls "$RIG"/work/fp-run/*/handoff/*-request.txt 2>/dev/null | head -1)
  if [ -n "$req" ] && [ "$served" -eq 0 ]; then
    served=1
    rf=$(sed -n 's/^receipt_file: //p' "$req")
    nonce=$(sed -n 's/^nonce: //p' "$req")
    runroot=$(dirname "$(dirname "$req")")
    echo "  request seen: $(basename "$req")"
    echo "    it names receipt_file: $rf"
    echo "    it names nonce:        $nonce"
    # what liam's command would have produced, as the request's run_exactly says
    printf 'ActiveStore enforcement is NotConfigurable; refusing\n' > "$runroot/b-setup.err"
    printf '\n' > "$runroot/b-setup.out"
    mkdir -p "$(dirname "$rf")"
    { echo "liam receipt"; echo "nonce: $nonce"; echo "exit=1"; } > "$rf"
    echo "    RECEIPT WRITTEN at exactly that path, carrying that nonce, exit=1 (a refusal)"
  fi
  sleep 3; waited=$((waited + 3))
done

alive=0; kill -0 "$DRIVER" 2>/dev/null && alive=1
if [ "$alive" -eq 1 ]; then
  echo "  BOUNDED OUT: driver still running ${BOUND}s after the receipt was written."
  echo "  Sending TERM — this also exercises a signal DURING a handoff wait."
  kill -TERM "$DRIVER" 2>/dev/null
fi
wait "$DRIVER"; rc=$?
cp "$RIG/work/actions.log" "$RIG/arm2-actions.log"

R=$(ls -d "$RIG"/work/fp-run/*/ 2>/dev/null | head -1)
echo
echo "  --- ordered actions requested:"; sed 's/^/      /' "$RIG/arm2-actions.log"
echo "  --- driver exit: $rc  (alive_at_bound=$alive)"
echo "  --- handoff + D1 + teardown evidence from findings.txt:"
grep -E 'HANDOFF|D1|TEARDOWN|ARM_B|SIGNAL|CLEANUP_BEGIN|STATE_MARKED' "$R/findings.txt" 2>/dev/null | sed 's/^/      /'
echo "  --- state markers on disk:"; ls "$R/state" 2>/dev/null | sed 's/^/      /'
