#!/usr/bin/env bash
set -u
GW=$1; LABEL=$2
OUT=$GW/.spt-lane1/$LABEL
mkdir -p "$GW/.spt-lane1" || exit 4
mkdir "$OUT" 2>/dev/null || { echo "REFUSE: $OUT exists" >&2; 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-percell-id*' } | Select-Object -ExpandProperty ProcessId) -join ','")
builders=$(ps_join "(Get-CimInstance Win32_Process | Where-Object { \$_.Name -in @('cargo.exe','rustc.exe') -and \$_.CommandLine -like '*hertz-percell-id*' } | Select-Object -ExpandProperty ProcessId) -join ','")
{
  echo "started: $(date -u +%FT%TZ)"
  echo "head: $(git rev-parse HEAD)"
  echo "dirty: $(git status --porcelain | grep -c '^ M')"
  echo "holders: [$holders]"
  echo "builders: [$builders]"
  # BOX-WIDE COUNT BESIDE THE PATH PREDICATE. cargo/rustc frequently report an
  # EMPTY CommandLine (a process we cannot open), so the filtered census above is
  # INTERMITTENTLY BLIND and its empty [] cannot be read as "quiet box". This
  # second number cannot see WHOSE they are, but it cannot be blind either.
  echo "builders-box-wide-count: $(ps_join "@(Get-CimInstance Win32_Process -Filter \"Name='cargo.exe' OR Name='rustc.exe' OR Name='cargo-nextest.exe'\").Count")"
  echo "arm: UNFILTERED A, per-cell A identity; before = fd296557 6/6 not-ready, helper ~64 s"
} > "$OUT/census.txt"
[ -z "$holders" ]  || { echo "REFUSE holders $holders" >&2; exit 5; }
[ -z "$builders" ] || { echo "REFUSE builders $builders" >&2; exit 5; }
cargo run -q -p xtask -- pool-claim --pool ./target --label hertz-percell-id > "$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"
RIG=$GW/.spt/twohost-web/$LABEL
for r in "$RIG"/{a,b}.raw; do
  [ -f "$r" ] || { echo "$(basename "$r") MISSING" >> "$OUT/census.txt"; 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 "not-ready: $(grep -c 'A not ready for the message yet' "$RIG/b.raw" 2>/dev/null)" >> "$OUT/census.txt"
echo "helper: $(grep 'helper_role_a' "$RIG/a.raw" 2>/dev/null | grep -E 'PASS|FAIL' | head -1)" >> "$OUT/census.txt"
echo "exits: a=$(cat "$RIG/a.exit" 2>/dev/null) b=$(cat "$RIG/b.exit" 2>/dev/null)" >> "$OUT/census.txt"
echo "finished: $(date -u +%FT%TZ)" >> "$OUT/census.txt"
