#!/bin/sh
# DF-5504 extraction: pull the production code VERBATIM out of the
# guest's own /usr/src tree.  Fails hard if the tree is not the audited
# one (md5-gated).
set -e
UC=/usr/src/sys/bus/u4b/serial/ucycom.c
US=/usr/src/sys/bus/u4b/serial/usb_serial.c

# audited tree (host) md5s
UC_MD5=c7b432ce2b994b1e580f3b00a7bb13e0
US_MD5=dc5c04dbc86dbccefdd06cdff3887e29

[ "`md5 -q $UC`" = "$UC_MD5" ] || { echo "MD5 MISMATCH: $UC"; exit 1; }
[ "`md5 -q $US`" = "$US_MD5" ] || { echo "MD5 MISMATCH: $US"; exit 1; }

OUT=${1:-.}

# --- ucycom.c verbatim: constants + softc + models + defaults + protos
{
	echo "/* VERBATIM ucycom.c:62-101 + 181-182 (md5 $UC_MD5) */"
	sed -n '62,101p;181,182p' $UC
	echo "/* VERBATIM ucycom.c:112,117-119 prototypes of the extracted"
	echo " * cfg-chain functions (the other declarations of 103-120 are"
	echo " * for functions this harness does not extract) */"
	sed -n '112p;117,119p' $UC
} > $OUT/uc5504_ucycom.inc.tmp1

# --- ucycom.c verbatim: cfg chain functions (order: write, pre_param,
# --- open, param -- prototypes above make order irrelevant)
{
	echo "/* VERBATIM ucycom.c:412-444 ucycom_cfg_write */"
	sed -n '412,444p' $UC
	echo "/* VERBATIM ucycom.c:446-472 ucycom_pre_param */"
	sed -n '446,472p' $UC
	echo "/* VERBATIM ucycom.c:299-306 ucycom_cfg_open */"
	sed -n '299,306p' $UC
	echo "/* VERBATIM ucycom.c:474-507 ucycom_cfg_param */"
	sed -n '474,507p' $UC
} >> $OUT/uc5504_ucycom.inc.tmp1

# strip the two transfer-callback prototypes we do not extract
# (ucycom_ctrl_write_callback / ucycom_intr_read_callback decls at
# ucycom.c:109-110): they are usb_callback_t typedefs, harmless to keep.
mv $OUT/uc5504_ucycom.inc.tmp1 $OUT/uc5504_ucycom.inc

# --- fix-modeled copy: the ONE production change of fix.diff applied
# --- with sed (`0, 1000)' -> `0, UCYCOM_CFG_TIMEOUT)') + renames so
# --- baseline and fixed variants coexist in one module.
{
	echo "/* fix-modeled extraction: ucycom.c verbatim + fix.diff change */"
	echo "#define UCYCOM_CFG_TIMEOUT 250	/* fix.diff */"
	sed -n '412,444p' $UC
	sed -n '299,306p' $UC
	sed -n '474,507p' $UC
} | sed -e 's/ucycom_cfg_write/ucycom_cfg_write_f/g' \
       -e 's/ucycom_cfg_open/ucycom_cfg_open_f/g' \
       -e 's/ucycom_cfg_param/ucycom_cfg_param_f/g' \
       -e 's/, 0, 1000)/, 0, UCYCOM_CFG_TIMEOUT)/' > $OUT/uc5504_fixed.inc

# --- usb_serial.c verbatim core wrappers, in dependency order
{
	echo "/* VERBATIM usb_serial.c:906-922 ucom_cfg_close (md5 $US_MD5) */"
	sed -n '906,922p' $US
	echo "/* VERBATIM usb_serial.c:756-780 ucom_cfg_open core */"
	sed -n '756,780p' $US
	echo "/* VERBATIM usb_serial.c:1619-1637 ucom_cfg_param core */"
	sed -n '1619,1637p' $US
	echo "/* VERBATIM usb_serial.c:635-680 ucom_queue_command */"
	sed -n '635,680p' $US
} > $OUT/uc5504_core.inc

md5 $OUT/*.inc
echo "extraction OK"
