#!/usr/bin/env bash
# usage: drive.sh <worktree> <outdir>
set -u
WT=$1; OUT=$2; MODE=${3:-all}; mkdir -p "$OUT"; PORT=9339
export T3CODE_HOME="$OUT/t3home"; mkdir -p "$T3CODE_HOME"
export T3CODE_DEV_SEED=0
cd "$WT/apps/desktop"
node scripts/build-browser-secret.mjs >/dev/null 2>&1
node_modules/electron/dist/electron --no-sandbox --disable-gpu --remote-debugging-port=$PORT dist-electron/main.cjs > "$OUT/electron.log" 2>&1 &
MAIN=$!
echo "main pid $MAIN" | tee -a "$OUT/timeline.txt"
desc() { local p=$1; for c in $(pgrep -P "$p"); do echo "$c"; desc "$c"; done; }
snap() { local tag=$1; echo "=== $tag $(date +%T.%3N)" >> "$OUT/timeline.txt"; node /tmp/issue-lead-26604-r1/repro/cdp-text.mjs $PORT >> "$OUT/timeline.txt" 2>&1; import -window root "$OUT/$tag.png" 2>/dev/null; }
sleep 25; snap t0-ready
echo "--- descendants before kill" >> "$OUT/timeline.txt"
for p in $(desc $MAIN); do echo "$p $(tr '\0' ' ' < /proc/$p/cmdline | cut -c1-160)" >> "$OUT/timeline.txt"; done
KILL=""
for p in $(desc $MAIN); do c=$(tr '\0' ' ' < /proc/$p/cmdline); case "$c" in *--type=renderer*|*--type=gpu-process*|*--type=utility*) KILL="$KILL $p";; *--type=*|*crashpad*) ;; *) [ "$(ps -o ppid= -p $p | tr -d ' ')" = "$MAIN" ] && KILL="$KILL $p";; esac; done
if [ "$MODE" != all ]; then K2=""; for p in $KILL; do c=$(tr '\0' ' ' < /proc/$p/cmdline); case "$MODE:$c" in renderer:*--type=renderer*) K2="$K2 $p";; backend:*--type=*) ;; backend:*) K2="$K2 $p";; esac; done; KILL=$K2; fi
echo "=== KILL (SIGTERM) $(date +%T.%3N):$KILL" >> "$OUT/timeline.txt"
kill -TERM $KILL
sleep 2; snap t2s
sleep 6; snap t8s
sleep 12; snap t20s
sleep 10; snap t30s
echo "--- main alive? $(kill -0 $MAIN 2>/dev/null && echo yes || echo no)" >> "$OUT/timeline.txt"
kill -TERM $MAIN; wait $MAIN
