#!/usr/bin/env bash
# R6: drive agentSessions.scan on the running HEAD dev server. Args: webPort serverPort serverPid
set -uo pipefail
C=/tmp/ev-23690/capture; D=$C/drivers; F=$C/fx-r6; WEB=$1; SRV=$2; SPID=$3
ORIGIN=http://localhost:$WEB; TOKEN=$(cat $C/.devtoken)
cd $HOME/wt/pr-23690/apps/server
cats() { # cat-shim log lines for the FIFO configs since line $1
  tail -n +$(( $1 + 1 )) $C/r6-cat.log | awk -v a="$F/ws/fifo-a/.git/config" -v b="$F/ws/fifo-b/.git/config" -v n="$F/ws/normal/.git/config" \
    '{t++} $3==a{fa++} $3==b{fb++} $3==n{nn++} END{printf "  cat execs: total=%d fifo-a/config=%d fifo-b/config=%d normal/config=%d\n", t, fa, fb, nn}'; }
lines() { wc -l < $C/r6-cat.log 2>/dev/null || echo 0; }
echo "## R6 HEAD dev server  $(date -u +%FT%TZ)  server pid=$SPID web=$WEB server=$SRV"
echo "### connection 1: 5 scans"; L=$(lines)
node $D/ws-scan.mjs $ORIGIN "$TOKEN" 5 conn1
cats $L
echo "per-scan cat lines (conn1):"; tail -n +$((L+1)) $C/r6-cat.log | sed "s#$F/ws/##"
LAST_END=$(date +%s.%N)
echo; echo "### HTTP after scans"
curl -s -o /dev/null -w '/.well-known/t3/environment (server port)  status=%{http_code} time=%{time_total}s\n' http://127.0.0.1:$SRV/.well-known/t3/environment
curl -s -o /dev/null -w '/.well-known/t3/environment (via vite)     status=%{http_code} time=%{time_total}s\n' $ORIGIN/.well-known/t3/environment
curl -s -o /dev/null -H 'Host: evtest.invalid' -w 'GET /index.html non-loopback Host -> static handler (fs exists/read on apps/web/dist) status=%{http_code} time=%{time_total}s\n' http://127.0.0.1:$SRV/index.html
sleep 5   # >3 s after the 2 s read deadline of the last blocked cat
echo; echo "### cat children of server pid $SPID ~5 s after last scan (ps -eo pid,ppid,etimes,stat,cmd)"
ps -eo pid,ppid,etimes,stat,cmd | awk -v p=$SPID 'NR==1 || ($2==p && $5 ~ /cat$/)'
echo "descendants of $SPID named cat: $(ps -eo pid,ppid,comm | awk -v p=$SPID '$2==p && $3=="cat"' | wc -l)"
echo "all cat processes on the box reading fx-r6 paths: $(ps -eo cmd | grep -c "^/usr/bin/cat -- $F" )"
echo; echo "### connection 2 (NEW WebSocket): 1 scan — memo lifetime"; L=$(lines)
node $D/ws-scan.mjs $ORIGIN "$TOKEN" 1 conn2
cats $L
echo; echo "### release FIFO: replace fifo-a/.git/config with a regular config at the same path"
rm -v $F/ws/fifo-a/.git/config && cp -v $F/fifo-a.config.real $F/ws/fifo-a/.git/config && ls -l $F/ws/fifo-a/.git/config
echo "### connection 3 (NEW WebSocket): 1 scan"; L=$(lines)
node $D/ws-scan.mjs $ORIGIN "$TOKEN" 1 conn3
cats $L
echo "### connection 3b: same check again on another connection"; L=$(lines)
node $D/ws-scan.mjs $ORIGIN "$TOKEN" 1 conn3b
cats $L
