#!/usr/bin/env bash
# One battery, one output dir, one writer. The lock is on the OUTPUT DIR, not
# the pool: two drivers may share a pool sequentially, but two writers into one
# raw set makes every line unattributable (measured 2026-09-08, runs 1 and 2).
set -u
cd "$(dirname "$0")"
out=.spt-fix5
mkdir -p "$out"

# Refuse loudly if another driver holds this output dir.
if ! ( set -o noclobber; echo "$$ $(date -u)" > "$out/.lock" ) 2>/dev/null; then
  echo "REFUSED: $out held by $(cat "$out/.lock" 2>/dev/null)"; exit 2
fi
trap 'rm -f "$out/.lock"' EXIT

# procs-before: the census is a FILE, not my say-so. A non-empty list means a
# previous run is still building into this pool and this one must not start.
before=$(powershell -NoProfile -Command "Get-CimInstance Win32_Process -Filter \"Name='cargo.exe' or Name='rustc.exe'\" | Where-Object { \$_.CommandLine -like '*ws272-w3*' } | Select-Object -Expand ProcessId" 2>/dev/null | tr -d '\r' | tr '\n' ' ')
echo "procs-before: [$before]" | tee "$out/census.txt"
if [ -n "${before// /}" ]; then
  echo "REFUSED: pool busy" | tee -a "$out/census.txt"; exit 2
fi

leg() { # leg <name> <cmd...>
  local name=$1; shift
  echo "=== $name $(date -u) ==="
  "$@" > "$out/$name.raw" 2>&1
  echo $? > "$out/$name.exit"
}
export CARGO_TARGET_DIR="C:/Users/decid/Documents/projects/spt-core/.worktrees/ws272-w3/target"
echo "pool: $CARGO_TARGET_DIR" | tee -a "$out/census.txt"
SPT_POOL_UNCHECKED=1 leg claim cargo run -q -p xtask -- pool-claim --pool "$CARGO_TARGET_DIR" --label ws272-w3-fix --foreign-pool
leg clippy  cargo clippy --workspace --all-targets -- -D warnings
leg nextest cargo nextest run -E '(package(spt-daemon) | package(spt-runtime) | package(spt-store)) & kind(lib)'
leg check   cargo run -q -p xtask -- check
leg treqs   traceable-reqs check

# A raw with 2 Summaries (two runs) and one with 0 (leg never ran) are DIFFERENT
# failures; name the count rather than passing silently.
n=$(grep -c '^ *Summary' "$out/nextest.raw" || true)
echo "nextest Summary count: $n" | tee -a "$out/census.txt"
[ "$n" = 1 ] || echo "REFUSED: Summary count $n is not 1 — this raw is not evidence" | tee -a "$out/census.txt"
echo "=== done $(date -u) ==="
