#!/usr/bin/env bash
# ============================================================================
# Rumpk ARM64 QEMU Runner
# ============================================================================
# Usage:
#   ./run_aarch64.sh          # Interactive boot
#   ./run_aarch64.sh test     # Automated boot test
# ============================================================================
set -euo pipefail
cd "$(dirname "$0")"

KERNEL="zig-out/bin/rumpk.elf"
DISK="build/disk_aarch64.img"

if [ ! -f "$KERNEL" ]; then
    echo "ERROR: $KERNEL not found. Run: zig build -Darch=aarch64"
    exit 1
fi

# Create disk image if missing (16MB for LittleFS)
if [ ! -f "$DISK" ]; then
    mkdir -p build
    dd if=/dev/zero of="$DISK" bs=1M count=16 2>/dev/null
    echo "Created $DISK (16MB)"
fi

MODE="${1:-interactive}"

# VirtIO MMIO devices for aarch64 virt
VIRTIO_NET="-device virtio-net-device,netdev=net0 -netdev user,id=net0"
VIRTIO_BLK="-device virtio-blk-device,drive=hd0 -drive if=none,id=hd0,format=raw,file=$DISK"

if [ "$MODE" = "test" ]; then
    echo "=== Rumpk ARM64 Boot Test ==="
    TIMEOUT=20

    LOGFILE=$(mktemp /tmp/rumpk-aarch64-XXXXXX.log)
    timeout "$TIMEOUT" qemu-system-aarch64 \
        -M virt -cpu cortex-a72 -m 512M \
        -nographic -serial mon:stdio \
        -kernel "$KERNEL" \
        $VIRTIO_NET $VIRTIO_BLK \
        -no-reboot >"$LOGFILE" 2>&1 || true

    cat "$LOGFILE"
    echo ""
    echo "=== Boot Checks ==="

    PASS=0
    FAIL=0

    check() {
        local label="$1"
        local pattern="$2"
        if grep -qa "$pattern" "$LOGFILE"; then
            echo "  [PASS] $label"
            PASS=$((PASS + 1))
        else
            echo "  [FAIL] $label"
            FAIL=$((FAIL + 1))
        fi
    }

    check "UART loopback"          "Loopback Test: PASS"
    check "aarch64_init reached"   "aarch64_init reached"
    check "GICv2 initialized"      "GICv2 initialized"
    check "Timer initialized"      "Timer initialized"
    check "Vectors installed"      "vectors installed"
    check "Nim handoff"            "Handing off to Nim"
    check "VirtIO-Net found"       "VirtIO-Net"
    check "VirtIO-Blk found"       "VirtIO-Block\|VirtIO-Blk\|Storage initialized"
    check "VirtIO init complete"   "Initialization Complete"

    TOTAL=$((PASS + FAIL))
    echo ""
    echo "=== Result: $PASS/$TOTAL ==="
    if [ "$FAIL" -gt 0 ]; then
        exit 1
    fi
else
    exec qemu-system-aarch64 \
        -M virt -cpu cortex-a72 -m 512M \
        -nographic -serial mon:stdio \
        -kernel "$KERNEL" \
        $VIRTIO_NET $VIRTIO_BLK
fi
