#!/bin/sh
# DF-0834 trigger.sh — fast foreground evidence capture.
# Emits every line to BOTH stdout (streamed over ssh) AND the log file,
# so the host receives the early ps snapshots before the system wedges.
LOG=/root/df0834/trigger.out
: > "$LOG"
emit() {
    echo "$@"
    echo "$@" >> "$LOG"
}

emit "=== DF-0834 trigger $(date +%T) ==="
emit "uname: $(uname -v)"
cd /root/df0834 || { emit "FATAL: no /root/df0834"; exit 2; }
IMG=df0834.img
MNT=/mnt/df0834

VNDEV=$(vnconfig -c vn "$IMG" 2>&1 | awk '{print $1}' | head -1)
emit "vn device: $VNDEV"
mkdir -p "$MNT"
mount -t ufs "/dev/$VNDEV" "$MNT"
emit "=== mounted; ls -li ==="
ls -li "$MNT" | while read line; do emit "$line"; done

emit "=== launching mv (background) ==="
cd "$MNT"
( mv S A/S_moved ) >/tmp/df0834_mvout 2>&1 &
MV_PID=$!
emit "mv pid=$MV_PID at $(date +%T)"
cd /

# ps snapshots at +1s intervals — capture before the system wedges.
for s in 1 2 3 4 5; do
    sleep 1
    emit "--- ps @+${s}s ---"
    ps -axo pid,stat,time,comm | awk -v p="$MV_PID" 'NR==1||$1==p' | while read line; do emit "$line"; done
done

# kill -9 attempt.
kill -9 "$MV_PID" 2>/dev/null
sleep 1
emit "--- after kill -9 ---"
if kill -0 "$MV_PID" 2>/dev/null; then
    emit "SIGKILL-PROOF: mv pid=$MV_PID survived kill -9"
    T1=$(ps -axo pid,time | awk -v p="$MV_PID" '$1==p{print $2}')
    sleep 3
    T2=$(ps -axo pid,time | awk -v p="$MV_PID" '$1==p{print $2}')
    emit "CPU time climb: t1=$T1 -> t2=$T2 (over 3s) => INFINITE LOOP in ufs_checkpath"
else
    emit "mv exited:"
    cat /tmp/df0834_mvout 2>/dev/null | while read line; do emit "$line"; done
fi
emit "=== trigger done $(date +%T) ==="
sync
