#!/usr/bin/env bash
# v3 — doyle's stale-path discriminator. ONE variable changes from r1: role A
# runs ONLY the helper cell, so B has no prior sighting of id_a at another port
# when the helper dial arrives. The rig source is UNCHANGED on purpose; adding
# the wall_ms stamps in the same run would confound two changes.
set -u
GW=$1; LABEL=$2
OUT=$GW/.spt-rider/$LABEL
mkdir -p "$GW/.spt-rider" || exit 4
mkdir "$OUT" 2>/dev/null || { echo "REFUSE: $OUT exists" >&2; exit 4; }
RIG=$GW/.spt/twohost-web/$LABEL
mkdir -p "$RIG" || exit 4
cd "$GW" || exit 9
ps_join() { powershell.exe -NoProfile -Command "$1" 2>/dev/null | tr -d '\r\n'; }
holders=$(ps_join "(Get-CimInstance Win32_Process | Where-Object { \$_.ExecutablePath -like '*hertz-65s-rider*' } | Select-Object -ExpandProperty ProcessId) -join ','")
builders=$(ps_join "(Get-CimInstance Win32_Process | Where-Object { \$_.Name -in @('cargo.exe','rustc.exe') -and \$_.CommandLine -like '*hertz-65s-rider*' } | Select-Object -ExpandProperty ProcessId) -join ','")
{
  echo "started: $(date -u +%FT%TZ)"
  echo "head: $(git rev-parse HEAD)"
  echo "dirty: $(git status --porcelain | wc -l) tracked changes"
  echo "holders: [$holders]"
  echo "builders: [$builders]"
  echo "arm: role A filtered to two_host_web_helper_role_a ONLY; role B unfiltered; rig source unchanged"
} > "$OUT/census.txt"
[ -z "$holders" ]  || { echo "REFUSE: holders $holders" >&2; exit 5; }
[ -z "$builders" ] || { echo "REFUSE: builders $builders" >&2; exit 5; }

unset OWL_SESSION_ID SPT_AGENT_ID SPT_ENDPOINT_ID SPT_HOME
export SPT_TWO_HOST=1 SPT_TWO_HOST_SECRET=rig-doyle-w1 SPT_TWO_HOST_PEER_IP=127.0.0.1 \
       SPT_TWO_HOST_WAIT_SECS=${WAIT:-240} SPT_TWO_HOST_PORT_A=7460 SPT_TWO_HOST_PORT_B=7470

cargo nextest run -p spt-daemon --test twohost_web --no-run > "$RIG/build.raw" 2>&1
echo $? > "$RIG/build.exit"
[ "$(cat "$RIG/build.exit")" = 0 ] || exit 5

SPT_TWO_HOST_ROLE=b cargo nextest run -p spt-daemon --test twohost_web --no-fail-fast --no-capture \
  > "$RIG/b.raw" 2>&1 &
BPID=$!
sleep 10
SPT_TWO_HOST_ROLE=a cargo nextest run -p spt-daemon --test twohost_web --no-fail-fast --no-capture \
  -E 'test(two_host_web_helper_role_a)' > "$RIG/a.raw" 2>&1
echo $? > "$RIG/a.exit"
wait "$BPID"; echo $? > "$RIG/b.exit"
for r in "$RIG"/{a,b}.raw; do
  n=$(grep -c 'Summary' "$r"); case "$n" in 1) v=OK;; 0) v=NEVER-RAN;; *) v=OVERLAP-VOID;; esac
  echo "$(basename "$r") Summary=$n $v" >> "$OUT/census.txt"
done
echo "not-ready-lines: b=$(grep -c 'A not ready for the message yet' "$RIG/b.raw")" >> "$OUT/census.txt"
echo "finished: $(date -u +%FT%TZ)" >> "$OUT/census.txt"
