#!/bin/sh
# DF-2462 run_fixed.sh -- A/B battery on the FIXED kernel.
# Scenarios S0..S6 + S5 (which PANICKED the baseline guest must now
# be survived) + a short S7.
set -u
cd "$(dirname "$0")"
ROOT=/home/maxx/dfbsd/dfbsd
VM="$ROOT/dfbsd-qemu/vm.sh"

run() { "$VM" run_root "$@"; }
usr() { "$VM" run_user "$@"; }

wait_busy() {
	i=0
	while [ $i -lt "$1" ]; do
		b=$(run 'sysctl -n debug.df2462.busy' 2>/dev/null)
		[ "$b" != "1" ] && return 0
		sleep 1
		i=$((i + 1))
	done
	echo "TIMEOUT waiting for busy=0" >&2
	return 1
}

{
	echo "=== DF-2462 FIXED-kernel battery $(date -u) ==="
	run 'uname -a'

	for s in 0 1 2 3 4; do
		echo "--- scenario S$s (fixed) ---"
		run "sysctl debug.df2462.run=$s"
		wait_busy 90 || true
		sleep 1
	done
	run 'sysctl -n debug.df2462.out'

	echo "--- scenario S6 (fixed): unprivileged userland reads in-window ---"
	run 'sysctl debug.df2462.run=6'
	sleep 6
	b=$(run 'sysctl -n debug.df2462.busy' 2>/dev/null)
	echo "S6 busy=$b (expect 1: teardown parked; on the FIXED tree the OIDs resolve to sessions[sid]=NULL)"
	usr 'id'
	usr 'sysctl debug.df2462.sess.7.stats'
	usr 'sysctl debug.df2462.sess.7.targetname'
	usr 'sysctl debug.df2462.sess.7.targeaddress'
	run 'sysctl debug.df2462.s6done=1'
	wait_busy 90 || true
	sleep 1
	run 'sysctl -n debug.df2462.out'
} 2>&1 | tee run_fixed.log

echo "--- scenario S5 (fixed): MUST SURVIVE (baseline panicked) ---"
{
	run 'sysctl debug.df2462.run=5'
	wait_busy 120 || true
	run 'sysctl -n debug.df2462.busy'
	run 'sysctl -n debug.df2462.out'
} 2>&1 | tee run_fixed_s5.log
sleep 5
if "$VM" status >/dev/null 2>&1; then
	echo "GUEST SURVIVED S5 on the FIXED kernel (baseline: Fatal trap 12)" | \
		tee -a run_fixed_s5.log
	run 'dmesg | tail -6' >> run_fixed_s5.log 2>&1
else
	echo "GUEST DOWN after S5 on the FIXED kernel -- fix incomplete!" | \
		tee -a run_fixed_s5.log
	"$VM" log 100 > panic_fixed.txt 2>&1 || true
fi

echo "--- short S7 (fixed) ---"
{
	usr 'sh -c "end=$(($(date +%s)+18)); i=0; while [ \$(date +%s) -lt \$end ]; do sysctl -qn debug.df2462.sess.7.stats 2>/dev/null; i=\$((i+1)); done; echo hammer_done \$i"' &
	HPID=$!
	sleep 2
	run 'sysctl debug.df2462.s7ms=8000'
	run 'sysctl debug.df2462.run=7'
	wait_busy 60 || true
	run 'sysctl -n debug.df2462.out'
	wait $HPID || true
} 2>&1 | tee run_fixed_s7.log
echo "fixed battery complete"
