#!/usr/bin/env bash
set -u
GW=$1; LABEL=$2
OUT=$GW/.spt-rider/$LABEL
if ! mkdir -p "$GW/.spt-rider" || ! mkdir "$OUT" 2>/dev/null; then
  echo "REFUSE: output dir $OUT already exists — a second writer into one raw set voids both runs" >&2
  exit 4
fi
cd "$GW" || exit 9
{
  echo "started: $(date -u +%FT%TZ)"
  echo "head: $(git rev-parse HEAD)"
  printf 'procs-before: ['
  powershell.exe -NoProfile -Command "(Get-CimInstance Win32_Process | Where-Object { \$_.ExecutablePath -like '*hertz-65s-rider*' } | Select-Object -ExpandProperty ProcessId) -join ','" 2>/dev/null | tr -d '\r'
  echo ']'
} > "$OUT/census.txt"
holders=$(grep -o 'procs-before: \[.*\]' "$OUT/census.txt" | sed 's/.*\[\(.*\)\]/\1/')
if [ -n "$holders" ]; then
  echo "REFUSE: pool holders present: $holders" >&2; exit 5
fi
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"
for r in "$GW/.spt/twohost-web/$LABEL"/*.raw; do
  [ -f "$r" ] || continue
  echo "$(basename "$r") Summary=$(grep -c 'Summary' "$r")" >> "$OUT/census.txt"
done
echo "finished: $(date -u +%FT%TZ)" >> "$OUT/census.txt"
