#!/usr/bin/env bash
# gate-w1b.sh — the REMAINING W1 (#249) gate legs at 8d980fdf after gate-w1.sh was killed 02:54:56Z
# (its two driver bugs: `--bins` twice on prebuild; pair-leg exit = the last grep's status, so a red
# baseline did not stop the mutation arms). Same pool, same OUT dir, NEW leg names so the first
# driver's records stay untouched. Mutation arms run only when BOTH role exit files of the baseline
# pair read 0 — the exit FILES, not the script status.
set -u
GW=/c/Users/decid/Documents/projects/spt-core/.worktrees/gate-w1-26a96d58
POOL='C:\Users\decid\Documents\projects\spt-core\.worktrees\ws272-w1\target'
OUT=$GW/.spt/gate-doyle
PAIR=$GW/.spt/twohost-web
mkdir -p "$OUT"; cd "$GW" || exit 9
export CARGO_TARGET_DIR="$POOL"
unset OWL_SESSION_ID SPT_AGENT_ID SPT_ENDPOINT_ID SPT_HOME SPT_POOL_UNCHECKED
env | grep -E '^(OWL_SESSION_ID|SPT_AGENT_ID|SPT_ENDPOINT_ID|SPT_POOL_UNCHECKED)=' > "$OUT/env-leak-b.txt"; echo "leaked=$(wc -l < "$OUT/env-leak-b.txt")" >> "$OUT/env-leak-b.txt"
leg() { # name cmd...
  local n=$1; shift
  echo "[$(date -u +%H:%M:%SZ)] LEG $n START" >> "$OUT/driver.log"
  "$@" > "$OUT/$n.raw" 2>&1; local e=$?
  echo "$e" > "$OUT/$n.exit"
  echo "[$(date -u +%H:%M:%SZ)] LEG $n EXIT $e summaries=$(grep -c 'Summary \[' "$OUT/$n.raw") panics=$(grep -c 'panicked at' "$OUT/$n.raw") free_gb=$(df -BG --output=avail /c 2>/dev/null | tail -1 | tr -dc 0-9)" >> "$OUT/driver.log"
}
pair_ok() { # label -> 0 iff both role exit files exist and read 0
  [ "$(cat "$PAIR/$1/a.exit" 2>/dev/null)" = "0" ] && [ "$(cat "$PAIR/$1/b.exit" 2>/dev/null)" = "0" ]
}
echo "gate-w1b battery at $(git rev-parse --short HEAD) dirty=$(git status --short -uno | wc -l) $(date -u +%FT%TZ)" >> "$OUT/driver.log"
echo "procs-before: cargo=$(tasklist | grep -ci '^cargo' ) nextest=$(tasklist | grep -ci nextest) spt_from_pool=$(wmic process where "ExecutablePath like '%ws272-w1%'" get ProcessId 2>/dev/null | grep -c '[0-9]')" >> "$OUT/driver.log"

leg prebuild2  cargo build -p spt -p mock-adapter --bins
leg pair-none2 bash .spt/twohost-web-local.sh "$GW" none2 none
if pair_ok none2; then
  leg pair-mutA2 bash .spt/twohost-web-local.sh "$GW" mutA2 A
  leg pair-mutB  bash .spt/twohost-web-local.sh "$GW" mutB B
else
  echo "[$(date -u +%H:%M:%SZ)] mutation arms SKIPPED: baseline pair none2 a.exit=$(cat "$PAIR/none2/a.exit" 2>/dev/null) b.exit=$(cat "$PAIR/none2/b.exit" 2>/dev/null)" >> "$OUT/driver.log"
fi
leg mdbook     mdbook build docs-site
echo "[$(date -u +%H:%M:%SZ)] BATTERY DONE" >> "$OUT/driver.log"
echo "procs-after: cargo=$(tasklist | grep -ci '^cargo') nextest=$(tasklist | grep -ci nextest) spt_from_pool=$(wmic process where "ExecutablePath like '%ws272-w1%'" get ProcessId 2>/dev/null | grep -c '[0-9]')" >> "$OUT/driver.log"
