#!/bin/sh
# DF-4648 / DF-4649 / DF-4650 fix validation (guest).
# Applies the three fix.diffs to a copy of the pristine guest ar2316.c,
# re-extracts the (patched) function bodies verbatim, rebuilds the
# harness against them and re-runs all three modes.  Success criteria:
#   mode 1: NO overflow past pcdacTable[128]
#   mode 2: early return, no wild-read propagation, no uninit read
#   mode 3: completes without the wild-address SIGSEGV
set -e
cd /root/df2316

cp ar2316_src.c ar2316_fixed.c
patch -p1 ar2316_fixed.c < fixA.diff
patch -p1 ar2316_fixed.c < fixB.diff
patch -p1 ar2316_fixed.c < fixC.diff
echo PATCHES_APPLIED

awk '
  !f && /^GetLowerUpperIndex\(int16_t v/ { print prev; f=1 }
  f { print; if ($0 ~ /^#undef VpdTable_I/) { getline; print; exit } }
  { prev = $0 }
' ar2316_fixed.c > ar2316_extracted.inc
wc -l ar2316_extracted.inc

cc -O2 -Wall -Wno-pointer-sign -o ar2316_harness_fixed ar2316_harness.c
echo FIXED_BUILD_OK

echo "=== PATCHED mode 1 (expect: NO overflow) ==="
./ar2316_harness_fixed 1 || echo "exit=$? (1 == no overflow detected)"
echo "=== PATCHED mode 2 (expect: ret=0, no 0x5A5A propagation, sentinel minPower) ==="
./ar2316_harness_fixed 2 || echo "exit=$?"
echo "=== PATCHED mode 3 (expect: completes, no SIGSEGV at wild address) ==="
./ar2316_harness_fixed 3 || echo "exit=$?"
