#!/bin/sh
# run_fixed.sh -- A/B fix validation on the patched kernel.
# 1. apply fix.diff to the guest's /usr/src copy (audit-side sys/ is
#    never touched), 2. quick.sh rebuild + reboot, 3. re-run the exact
#    same battery, 4. un-patch the guest source again.
set -e
cd "$(dirname "$0")"
ROOT=/home/maxx/dfbsd/dfbsd
CFG=$ROOT/dfbsd-qemu/config
SSH="ssh -F $CFG -o ConnectTimeout=8 -o BatchMode=yes dfbsd"
SCP="scp -F $CFG -o ConnectTimeout=8 -o BatchMode=yes"
VM=$ROOT/dfbsd-qemu/vm.sh
rsh() { printf '%s\n' "$1" | $SSH /bin/sh; }

echo '=== applying fix.diff to guest /usr/src ==='
$SCP fix.diff dfbsd:/root/fix2269.diff
rsh 'cd /usr/src && patch -p1 --dry-run < /root/fix2269.diff && patch -p1 < /root/fix2269.diff'

echo '=== rebuild (quickkernel) + reboot ==='
./quick.sh

echo '=== re-running the exact battery ==='
timeout 90 $VM run_root 'sysctl debug.df2269.matrix=1' > run_fixed_matrix.log 2>&1 || true
timeout 120 $VM run_root 'sysctl debug.df2269.formats=1' > run_fixed_formats.log 2>&1 || true
timeout 90 $VM run_root 'sysctl debug.df2269.leak=1' > run_fixed_leak.log 2>&1 || true
timeout 180 $VM run_root 'sysctl debug.df2269.repeat=10' > run_fixed_repeat.log 2>&1 || true
$VM run_root 'dmesg | grep DFH2269' > run_fixed_dmesg.log 2>&1 || true
echo "captured $(wc -l < run_fixed_dmesg.log) DFH2269 lines on the FIXED kernel"

echo '=== reverting the guest source patch ==='
rsh 'cd /usr/src && patch -R -p1 < /root/fix2269.diff'
rsh 'grep -c "resid > (u_int32_t)length" /usr/src/sys/bus/cam/scsi/scsi_cd.c || echo reverted'
