#!/bin/sh
#
# mkimage.sh - DF-2606 full reproduction flow (run as root in the DragonFly guest)
#
# Rebuilds the crafted hammer2 image from scratch:
#   1. newfs_hammer2 a fresh 2GB image file (PFS label "LOCAL")
#   2. mount it via vn, create 24 files + a subdir, clean unmount
#   3. keep a pristine copy
#   4. h2keybits patch: INDIRECT slot keybits 63 -> 65 (all integrity
#      checks -- XXH64 chain checks + volume-header iCRC32s -- fixed up,
#      so the kernel sees fully valid metadata)
#   5. dump both topologies
#
# usage: ./mkimage.sh [workdir]   (default /root/df2606)
# needs: ./h2keybits (built by build.sh) in the same directory

set -e
D=${1:-/root/df2606}
cd "$D"

echo "=== [1/5] fresh 2GB image + newfs_hammer2"
rm -f h2.img h2.pristine.img
truncate -s 2G h2.img
newfs_hammer2 h2.img > mkfs.log 2>&1
grep -E 'PFS|Volume' mkfs.log

echo "=== [2/5] mount, populate 24 files + sub, clean unmount"
vnconfig -c vn0 "$D/h2.img"
mount_hammer2 /dev/vn0@LOCAL /mnt
i=1
while [ $i -le 24 ]; do
	printf "DF2606 payload file number %03d\n" $i > /mnt/$(printf "f%03d" $i)
	i=$((i+1))
done
mkdir /mnt/sub
echo nested > /mnt/sub/note.txt
echo "entries created: $(ls /mnt | wc -l)"
sync
cd "$D"
umount /mnt
vnconfig -d vn0

echo "=== [3/5] pristine copy"
cp h2.img h2.pristine.img

echo "=== [4/5] patch INDIRECT slot 1 keybits -> 65 (checks fixed up)"
./h2keybits h2.img patch 65 1 | tee patch.log

echo "=== [5/5] dump topologies"
./h2keybits h2.pristine.img dump > dump.pristine.log 2>&1
./h2keybits h2.img dump > dump.patched.log 2>&1
grep -E "keybits=6[0-9]|keybits=[0-9] " dump.patched.log
echo "done."
