#!/bin/bash
# ============================================================================
# build.sh — HDGL Phi-Lattice Analog Substrate
# ============================================================================
# Builds all binaries from source. One command.
#
# Prerequisites: nasm >= 2.14, gcc >= 9
# No Docker. No Make. No CMake. No Python.
#
# Output: bin/hdgl_router64.img (ready to dd to hardware or run in QEMU)
#
# Usage:
#   bash build.sh              # build everything
#   bash build.sh --qemu       # build + run in QEMU (requires qemu-system-x86_64)
#   bash build.sh --flash /dev/sdX  # build + flash to hardware
#
# QEMU test command (after build):
#   qemu-system-x86_64 -drive file=bin/hdgl_router64.img,format=raw,if=ide \
#     -boot order=c -m 256M -serial stdio -no-reboot -display none
#
# At Router64> prompt:
#   Router64> help          -- list commands
#   Router64> analog        -- show phi-lattice field
#   Router64> dn            -- show Dn aggregate (0xFFFF0000 pattern)
#   Router64> alpine 512 16896  -- boot Alpine on analog substrate
#
# ============================================================================
set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SRC="$SCRIPT_DIR/src"
BIN="$SCRIPT_DIR/bin"
mkdir -p "$BIN"

echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "  HDGL Phi-Lattice Analog Substrate — Build"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

# ── [1] Boot chain assembly ──────────────────────────────────────────────────
echo "[1] MBR (512B)..."
nasm -f bin "$SRC/hdgl_mbr.asm" -o "$BIN/hdgl_mbr.bin"
[ "$(stat -c%s "$BIN/hdgl_mbr.bin")" -eq 512 ] || { echo "ERROR: MBR != 512B"; exit 1; }
echo "    OK"

echo "[2] Stage2 (512B)..."
nasm -f bin "$SRC/hdgl_stage2_router.asm" -o "$BIN/hdgl_stage2_router.bin"
[ "$(stat -c%s "$BIN/hdgl_stage2_router.bin")" -eq 512 ] || { echo "ERROR: Stage2 != 512B"; exit 1; }
echo "    OK"

echo "[3] Runtime64 (32768B — analog substrate + glyph-CA + float4096 + alpine handoff)..."
( cd "$SRC" && nasm -f bin hdgl_router64.asm -o "$BIN/hdgl_router64.bin" 2>&1 | grep -v warning ) || {
    echo "ERROR: Runtime64 assembly failed"
    exit 1
}
RSIZ=$(stat -c%s "$BIN/hdgl_router64.bin")
[ "$RSIZ" -eq 32768 ] || { echo "ERROR: Runtime64 = $RSIZ bytes (must be exactly 32768)"; exit 1; }
echo "    OK ($RSIZ bytes)"

echo "[4] Stage2-CD..."
nasm -f bin "$SRC/hdgl_stage2_cd.asm" -o "$BIN/hdgl_stage2_cd.bin"
echo "    OK"

echo "[5] UEFI stub..."
mkdir -p "$BIN/EFI/BOOT"
nasm -f bin "$SRC/hdgl_uefi_stub.asm" -o "$BIN/EFI/BOOT/BOOTX64.EFI"
echo "    OK"

# ── [2] Disk image ───────────────────────────────────────────────────────────
echo "[6] Disk image..."
FIRMWARE_SRC="$SRC/hdgl_firmware.hdgl"
FIRMWARE_SECTORS=$(( ($(wc -c < "$FIRMWARE_SRC") + 511) / 512 ))

# Start with 32MB image (room for kernel + initrd)
dd if=/dev/zero bs=512 count=65536 of="$BIN/hdgl_router64.img" 2>/dev/null

# Sector layout:
#   0        MBR (512B)
#   1        Stage2 (512B)
#   2-65     Runtime64 (64 sectors = 32KB)
#   66-...   Firmware HDGL source
#
# Kernel + initrd (embedded by build_initrd.sh or build_tables.sh):
#   512      Alpine/Linux kernel bzImage
#   16896    initramfs (our /init + phi_pool, from phi_pool.hdgl)
dd if="$BIN/hdgl_mbr.bin"           bs=512 count=1              seek=0  conv=notrunc of="$BIN/hdgl_router64.img" 2>/dev/null
dd if="$BIN/hdgl_stage2_router.bin" bs=512 count=1              seek=1  conv=notrunc of="$BIN/hdgl_router64.img" 2>/dev/null
dd if="$BIN/hdgl_router64.bin"      bs=512 count=64             seek=2  conv=notrunc of="$BIN/hdgl_router64.img" 2>/dev/null
dd if="$FIRMWARE_SRC"               bs=512 count=$FIRMWARE_SECTORS seek=66 conv=notrunc of="$BIN/hdgl_router64.img" 2>/dev/null

echo "    OK ($(stat -c%s "$BIN/hdgl_router64.img") bytes)"

# ── [3] phi_pool substrate daemon ───────────────────────────────────────────
# phi_pool is now defined in phi_pool.hdgl — the glyph rewrite engine
# materialises phi_pool_kuramoto.c from the glyph tree, then compiles it.
# phi_pool.c is no longer present; phi_pool.hdgl is the source of truth.
echo "[7] phi_pool (water glyph substrate — from phi_pool.hdgl)..."
if [ -f "$SCRIPT_DIR/phi_pool.hdgl" ]; then
    # Step 1: glyph rewrite engine materialises the C implementation
    if command -v hdgl_compile >/dev/null 2>&1; then
        hdgl_compile "$SCRIPT_DIR/phi_pool.hdgl"             --emit c --output "$SCRIPT_DIR/phi_pool_kuramoto.c"
        echo "    [hdgl] phi_pool.hdgl → phi_pool_kuramoto.c"
    else
        # Fallback: phi_pool_kuramoto.c already materialised alongside the hdgl
        echo "    [hdgl] using pre-materialised phi_pool_kuramoto.c"
    fi
    # Step 2: compile the materialised C
    if [ -f "$SCRIPT_DIR/phi_pool_kuramoto.c" ]; then
        gcc -O3 -fopenmp -o "$BIN/phi_pool"             "$SCRIPT_DIR/phi_pool_kuramoto.c" -lm
        echo "    OK ($(stat -c%s "$BIN/phi_pool") bytes, from phi_pool.hdgl)"
    else
        echo "    SKIP (phi_pool_kuramoto.c not materialised)"
    fi
else
    echo "    SKIP (phi_pool.hdgl not found)"
fi

# ── [4] ll_daemon substrate daemon ──────────────────────────────────────────
echo "[8] ll_daemon (8D Kuramoto substrate daemon)..."
if [ -f "$SCRIPT_DIR/ll_daemon.hdgl" ]; then
    [ -f "$SCRIPT_DIR/ll_daemon.c" ] || { command -v hdgl_compile >/dev/null 2>&1 && hdgl_compile "$SCRIPT_DIR/ll_daemon.hdgl" --emit c --output "$SCRIPT_DIR/ll_daemon.c"; }
    gcc -O2 -o "$BIN/ll_daemon" "$SCRIPT_DIR/ll_daemon.c" -lm
    echo "    OK (from ll_daemon.hdgl)"
else
    echo "    SKIP (ll_daemon.hdgl not found)"
fi

echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "  BUILD COMPLETE"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo "  MBR:       bin/hdgl_mbr.bin           (512B)"
echo "  Stage2:    bin/hdgl_stage2_router.bin  (512B)"
echo "  Runtime64: bin/hdgl_router64.bin       (32768B)"
echo "  Disk:      bin/hdgl_router64.img       (32MB)"
echo ""
echo "  NEXT STEPS:"
echo "  1. Embed Alpine kernel + initramfs:  bash build_initrd.sh"
echo "  2. Embed precomputed tables:         bash build_tables.sh"
echo "  3. Flash to hardware:                dd if=bin/hdgl_router64.img of=/dev/sdX bs=512 oflag=sync"
echo "  4. Or test in QEMU (see below)"
echo ""
echo "  QEMU TEST:"
echo "  qemu-system-x86_64 \\"
echo "    -drive file=bin/hdgl_router64.img,format=raw,if=ide \\"
echo "    -boot order=c -m 256M -serial stdio -no-reboot -display none"
echo ""
echo "  At Router64>:"
echo "    analog          # phi-lattice field display"
echo "    dn              # Dn aggregate (0xFFFF0000 pattern)"
echo "    prismatic       # 4096-strand tally"
echo "    alpine 512 16896 # boot Alpine on analog substrate"
echo ""

# ── Handle --qemu flag ───────────────────────────────────────────────────────
if [ "${1}" = "--qemu" ]; then
    echo "  Booting in QEMU..."
    qemu-system-x86_64 \
        -drive "file=bin/hdgl_router64.img,format=raw,if=ide" \
        -boot order=c -m 256M -serial stdio -no-reboot -display none
fi

# ── Handle --flash flag ──────────────────────────────────────────────────────
if [ "${1}" = "--flash" ] && [ -n "${2}" ]; then
    echo "  Flashing to ${2}..."
    echo "  WARNING: This will DESTROY all data on ${2}"
    read -p "  Type YES to confirm: " confirm
    if [ "$confirm" = "YES" ]; then
        dd if=bin/hdgl_router64.img of="${2}" bs=4M conv=fsync status=progress
        sync
        echo "  Flash complete. Connect COM1 at 9600 8N1 and power on."
    else
        echo "  Cancelled."
    fi
fi
