#!/usr/bin/env bash
# W0 head chain on kitsubito (todlando 2026-09-06): wait for the earlier driver
# (pid $1) to exit, record its exit files, reset the lane to head $2, run the
# full battery there, then the Am.2 smoke. Detached; progress in $LOG, DONE
# marker at the end so a poller can tell finished from capped.
set -u
OLD_PID="$1"; HEAD="$2"
cd ~/spt-w1/.worktrees/ws272-w0 || exit 2
OUT=.spt/gate-head; mkdir -p "$OUT"
LOG="$OUT/chain.log"; : > "$LOG"
say() { echo "$(date -u +%H:%M:%SZ) $*" >> "$LOG"; }
capped=1
for i in $(seq 1 480); do
  kill -0 "$OLD_PID" 2>/dev/null || { capped=0; break; }
  sleep 5
done
say "old-driver-gone capped=$capped"
say "old-nextest.exit=$(cat .spt/gate-am2/nextest.exit 2>/dev/null || echo MISSING) old-mdbook.exit=$(cat .spt/gate-am2/mdbook.exit 2>/dev/null || echo MISSING)"
grep -E "Summary|^\s+FAIL" .spt/gate-am2/nextest.raw | sort -u | head -8 >> "$LOG"
if [ "$capped" = 1 ]; then say "ABORT: old driver still alive at cap"; echo DONE >> "$LOG"; exit 3; fi
git fetch -q origin build/ws272-w0 && git reset -q --hard "$HEAD"
say "HEAD=$(git rev-parse HEAD)"
python3 .github/ci/ws272-w0.py --run --hold-released --output "$OUT" > "$OUT/driver.log" 2>&1
say "driver-exit=$?"
for f in "$OUT"/*.exit; do printf "%s=%s " "$(basename "$f" .exit)" "$(cat "$f")"; done >> "$LOG"; echo >> "$LOG"
grep -E "Summary|^\s+FAIL" "$OUT/nextest.raw" 2>/dev/null | sort -u | head -8 >> "$LOG"
python3 .spt/gate/w0-smoke-am2.py > "$OUT/smoke.raw" 2>&1
say "smoke-script-exit=$? smoke.exit=$(cat "$OUT/smoke.exit" 2>/dev/null || echo MISSING)"
grep -E "^(FAIL|SMOKE)" "$OUT/smoke.raw" >> "$LOG"
echo DONE >> "$LOG"
