#!/usr/bin/env bash
# v2 — NEW FILE on purpose: .spt-rider.sh is running, and bash reads a script
# incrementally, so editing one mid-flight resumes at a byte offset into
# different text. Never rewrite a running driver.
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 — two writers into one raw set voids both runs" >&2; exit 4; }
cd "$GW" || exit 9

# TWO censuses, because they answer DIFFERENT questions and v1 conflated them:
#   holders  = processes whose EXE lives in this pool  -> the LNK1104 class
#              (a leftover test binary holds the .exe the next build must write)
#   builders = processes whose command line names this worktree -> the overlap
#              class (a concurrent cargo building INTO the pool). cargo and
#              rustc live under ~/.cargo and ~/.rustup, so the holders predicate
#              CANNOT see them; v1 had only holders and would have reported a
#              live build as an empty pool.
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 (a HEAD line on a dirty tree names bytes that are not what ran)"
  echo "holders: [$holders]"
  echo "builders: [$builders]"
} > "$OUT/census.txt"
[ -z "$holders" ]  || { echo "REFUSE: pool holders $holders" >&2; exit 5; }
[ -z "$builders" ] || { echo "REFUSE: concurrent builders $builders" >&2; exit 5; }

cargo run -q -p xtask -- pool-claim --pool ./target --label hertz-65s-rider > "$OUT/claim.raw" 2>&1
echo $? > "$OUT/claim.exit"
[ "$(cat "$OUT/claim.exit")" = 0 ] || exit 6
bash "$GW/.spt/rig/twohost-web-local.sh" "$GW" "$LABEL" none > "$OUT/driver.raw" 2>&1
echo $? > "$OUT/driver.exit"
# Three-valued, not a bare equality: 2 = overlap, 0 = the leg never ran.
for r in "$GW/.spt/twohost-web/$LABEL"/*.raw; do
  [ -f "$r" ] || continue
  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 "finished: $(date -u +%FT%TZ)" >> "$OUT/census.txt"
