#!/bin/sh
# prep.sh -- one-time guest preparation for the pnpparse.c rig (DF-2316).
# Files are pushed to /root/pnp from the host.  The guest's /usr/src is the
# build scratch; the host-side sys/ tree is never modified.
set -e
cd /root/pnp

# 0. VERBATIM GATE: the guest's pnpparse.c must be byte-identical to the
#    audited tree (pristine sha256).  Refuse to prep a patched tree unless
#    PNPH_ALLOW_PATCHED=1 (fix-validation phase).
PRISTINE=4b13638c30fcb3cfae135711d2e4275f500edfc0cb3d35857e777399b25696a3
GOT=$(sha256 -r /usr/src/sys/bus/isa/pnpparse.c | awk '{print $1}')
if [ "$GOT" != "$PRISTINE" ]; then
	if [ "${PNPH_ALLOW_PATCHED:-0}" = 1 ]; then
		echo "VERBATIM_CHECK pnpparse.c PATCHED $GOT (pristine=$PRISTINE) -- allowed"
	else
		echo "VERBATIM_CHECK pnpparse.c PATCHED $GOT (pristine=$PRISTINE) -- REFUSING"
		exit 3
	fi
else
	echo "VERBATIM_CHECK pnpparse.c PRISTINE $GOT"
fi

# 1. stock pnp.c must be IN the build (undo any DF-2314/2315 state)
sed -e 's#^bus/isa/pnp\.c[[:space:]].*#bus/isa/pnp.c			optional isa#' \
    /usr/src/sys/conf/files > /tmp/files.a && mv /tmp/files.a /usr/src/sys/conf/files

# 2. drop the stock pnpparse.c unit (its TU is compiled inside
#    pnp_harness.c) and register ours.
install -m 644 pnp_harness.c pnph.h /usr/src/sys/bus/isa/
sed -e 's#^bus/isa/pnpparse\.c[[:space:]].*#bus/isa/pnpparse.c		optional pnp_stock_disabled#' \
    /usr/src/sys/conf/files > /tmp/files.b && mv /tmp/files.b /usr/src/sys/conf/files
grep -q pnp_harness.c /usr/src/sys/conf/files || \
    printf 'bus/isa/pnp_harness.c		optional pnp_harness\n' \
        >> /usr/src/sys/conf/files
grep -n 'bus/isa/pnp' /usr/src/sys/conf/files

# 3. kernel config: stock generic + the harness device
if [ ! -f /usr/src/sys/config/PNPH ]; then
	cp /usr/src/sys/config/X86_64_GENERIC /usr/src/sys/config/PNPH
	printf '\n# pnpparse.c audit rig (DF-2316)\ndevice\t\tpnp_harness\n' \
	    >> /usr/src/sys/config/PNPH
fi

# 4. panic behavior: no ddb, so the page-boundary fault reboots and the
#    serial log carries the panic text
grep -q debugger_on_panic /etc/sysctl.conf || \
    echo 'debug.debugger_on_panic=0' >> /etc/sysctl.conf
sysctl debug.debugger_on_panic=0

# 5. build the userland trigger
cc -O -Wall -o pnphctl pnphctl.c
ls -l pnphctl
echo PREP_OK
