#!/usr/bin/env bash
# doyle's gate driver for respin lane 2 (test/272-gateway-spool-envelope-repin) in the gate tree.
# Form: sentinel-seeded exit files; holder guard BEFORE any cargo (kills only spt.exe whose
# ExecutablePath is under THIS tree's target, refuses exit 5 if any remain); daemon-launching
# e2e cells single-threaded; verdict only from exit files.
set -u
cd "$(dirname "$0")" || exit 3
O=.spt-gate-r2l4
[ -e "$O" ] && { echo "REFUSE: outdir $O exists"; exit 4; }
mkdir -p "$O"
for l in holders build clippy treqs; do echo 'VOID:unfinished' > "$O/$l.exit"; done
unset OWL_SESSION_ID SPT_AGENT_ID SPT_ENDPOINT_ID SPT_HOME
TREE_WIN=$(cygpath -w "$(pwd)")
{
  echo "head=$(git rev-parse HEAD)"
  echo "start=$(date -u +%H:%M:%SZ)"
  echo "tree=$TREE_WIN"
  echo "tracked_dirty=$(git status --porcelain --untracked-files=no | wc -l) untracked=$(git status --porcelain | grep -c '^??')"
  echo "child_env_perch_vars=$(env | grep -cE '^(OWL_SESSION_ID|SPT_AGENT_ID|SPT_ENDPOINT_ID|SPT_HOME)=')"
} > "$O/census.txt"
# holder guard: spt.exe rooted in this tree's target, verified per pid
KILLED=0; LEFT=0
for pid in $(powershell -NoProfile -Command "Get-CimInstance Win32_Process -Filter \"Name='spt.exe'\" | % ProcessId"); do
  p=$(powershell -NoProfile -Command "(Get-CimInstance Win32_Process -Filter 'ProcessId=$pid').ExecutablePath")
  case "$p" in
    "$TREE_WIN"\\target\\*) powershell -NoProfile -Command "Stop-Process -Id $pid -Force" && KILLED=$((KILLED+1)) ;;
    *) LEFT=$((LEFT+1)) ;;
  esac
done
sleep 2
REMAIN=0
for pid in $(powershell -NoProfile -Command "Get-CimInstance Win32_Process -Filter \"Name='spt.exe'\" | % ProcessId"); do
  p=$(powershell -NoProfile -Command "(Get-CimInstance Win32_Process -Filter 'ProcessId=$pid').ExecutablePath")
  case "$p" in "$TREE_WIN"\\target\\*) REMAIN=$((REMAIN+1)) ;; esac
done
echo "holders killed_mine=$KILLED left_not_mine=$LEFT remaining=$REMAIN" >> "$O/census.txt"
if [ "$REMAIN" -ne 0 ]; then echo 'VOID:holders-in-pool' > "$O/holders.exit"; echo "REFUSE: $REMAIN holders remain"; exit 5; fi
echo 0 > "$O/holders.exit"
echo "builders_box_wide_at_start=$(powershell -NoProfile -Command "(Get-CimInstance Win32_Process | ? { \$_.Name -match '^(cargo|rustc|clippy-driver|cargo-nextest)\.exe$' } | % ProcessId) -join ','")" >> "$O/census.txt"
# fixtures + test bins
cargo build -p mock-adapter --bins > "$O/build.raw" 2>&1 && cargo build -p spt-daemon --bin service_fixture >> "$O/build.raw" 2>&1 && cargo build -p spt --bins >> "$O/build.raw" 2>&1 && cargo nextest run -p spt --no-run >> "$O/build.raw" 2>&1
echo $? > "$O/build.exit"
cargo clippy --workspace --all-targets -- -D warnings > "$O/clippy.raw" 2>&1
echo $? > "$O/clippy.exit"
traceable-reqs check > "$O/treqs.raw" 2>&1
echo $? > "$O/treqs.exit"
echo "phaseA_end=$(date -u +%H:%M:%SZ)" >> "$O/census.txt"
echo phaseA done
