#!/bin/bash
# Usage: run-recovery.sh <label> <worktree>. Startup with failing CLI, switch to healthy, then one held subscription.
set -u
R=/tmp/issue-lead-26775-r1/repro; LABEL=$1; WT=$2
RUN=$R/$LABEL-$(date +%H%M%S); mkdir -p $RUN/home; echo fail > $RUN/mode
cd $WT/apps/server
PATH="$R/bin-switch:$PATH" FAKE_TAILSCALE_MODE=$RUN/mode FAKE_TAILSCALE_LOG=$RUN/calls.log T3CODE_DEV_SEED=0 node src/bin.ts serve --base-dir $RUN/home --port 38775 --host 127.0.0.1 > $RUN/server.log 2>&1 &
PID=$!
for i in $(seq 1 60); do grep -q "Listening on" $RUN/server.log && break; sleep 1; done
TOKEN=$(node src/bin.ts auth session issue --base-dir $RUN/home --token-only --ttl 1h | grep -v '^$' | tail -1)
sleep 6  # let any startup read settle as a failure
echo ok > $RUN/mode
echo "[$LABEL] head $(git -C $WT rev-parse --short HEAD): startup with failing CLI, CLI healthy before connect"
node $R/subscribe-hold.mjs 38775 "$TOKEN" 8000
echo "tailscale calls:"; cat $RUN/calls.log
kill $PID; wait $PID 2>/dev/null
