#!/bin/bash
# ============================================================================
# build_initrd.sh — Build Alpine initramfs with phi_pool analog substrate
# phi_pool source: phi_pool.hdgl (glyph tree) → phi_pool_kuramoto.c (materialised C)
# ============================================================================
#
# Builds a minimal initramfs containing:
#   /init          — HDGL phi-lattice init (reads hdgl.dn + hdgl.tick)
#   /sbin/phi_pool — Water glyph substrate daemon (from phi_pool.hdgl, UFE-grounded)
#   /sbin/ll_daemon — 8D Kuramoto fallback substrate
#   /bin/busybox   — Static busybox for sh, mount, cat, etc.
#
# The /init script:
#   1. Reads genome_fp (hdgl.dn) and tick from kernel cmdline
#   2. Starts phi_pool as background daemon (Kuramoto-wave phase field, S¹×ℝ⁺)
#   3. phi_pool drives 𝓛ₙ(z) eigenmodes from genome_fp → /lattice/slots/
#   4. /lattice/slots/1..4096 contain live Chladni eigenmode amplitudes
#   5. Prints proof: D-slot values, FIRE indicators at sqrt(phi) threshold
#
# After build, embed with:
#   dd if=bin/hdgl_initrd.img of=bin/hdgl_router64.img bs=512 seek=16896 conv=notrunc
#
# ============================================================================
set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BIN="$SCRIPT_DIR/bin"
TMPDIR_FS="$BIN/initrd_build"

mkdir -p "$BIN"
rm -rf "$TMPDIR_FS"
mkdir -p "$TMPDIR_FS"

echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "  Building initramfs with water glyph analog substrate"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

# ── Directory tree ───────────────────────────────────────────────────────────
echo "[1] Creating directory tree..."
for d in bin sbin dev proc sys run tmp etc mnt; do
    mkdir -p "$TMPDIR_FS/$d"
done
mkdir -p "$TMPDIR_FS/run/lattice"
mkdir -p "$TMPDIR_FS/lattice/slots"
mkdir -p "$TMPDIR_FS/mnt/root"
echo "    OK"

# ── Busybox ──────────────────────────────────────────────────────────────────
echo "[2] Copying busybox..."
BUSYBOX=$(which busybox || echo /bin/busybox)
[ -f "$BUSYBOX" ] || { echo "ERROR: busybox not found. Install busybox-static."; exit 1; }
cp "$BUSYBOX" "$TMPDIR_FS/bin/busybox"
chmod +x "$TMPDIR_FS/bin/busybox"
cd "$TMPDIR_FS/bin"
for cmd in sh ash cat ls mkdir mount umount cp mv rm echo printf grep \
           sed awk cut sort head tail wc find sleep chmod chown ln mdev \
           switch_root nohup kill; do
    ln -sf busybox $cmd 2>/dev/null || true
done
ln -sf ../bin/busybox ../sbin/init
ln -sf ../bin/busybox ../sbin/switch_root
cd "$SCRIPT_DIR"
echo "    OK"

# ── phi_pool — water glyph substrate (from phi_pool.hdgl) ───────────────────
# phi_pool is defined in phi_pool.hdgl — glyph rewrite engine materialises
# phi_pool_kuramoto.c, then gcc compiles it into the static binary.
# phi_pool.c is no longer present. phi_pool.hdgl is the source of truth.
echo "[3] Building phi_pool (water glyph substrate, from phi_pool.hdgl)..."
if [ -f "$SCRIPT_DIR/phi_pool.hdgl" ]; then
    # Materialise C from glyph tree if engine available
    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"
    fi
    # Compile materialised C to static binary
    if [ -f "$SCRIPT_DIR/phi_pool_kuramoto.c" ]; then
        gcc -O3 -static -fopenmp -o "$TMPDIR_FS/sbin/phi_pool" \
            "$SCRIPT_DIR/phi_pool_kuramoto.c" -lm
        echo "    OK ($(stat -c%s "$TMPDIR_FS/sbin/phi_pool") bytes, static, from hdgl)"
    else
        echo "    SKIP: phi_pool_kuramoto.c not materialised"
    fi
else
    echo "    SKIP: phi_pool.hdgl not found"
fi

# ── ll_daemon — Kuramoto fallback ────────────────────────────────────────────
echo "[4] Compiling ll_daemon (8D Kuramoto fallback)..."
if [ -f "$SCRIPT_DIR/ll_daemon.c" ]; then
    gcc -O2 -static -o "$TMPDIR_FS/sbin/ll_daemon" \
        "$SCRIPT_DIR/ll_daemon.c" -lm
    echo "    OK"
else
    echo "    SKIP: ll_daemon.c not found"
fi

# ── /init script ─────────────────────────────────────────────────────────────
echo "[5] Writing /init..."
cp "$SCRIPT_DIR/alpine_init" "$TMPDIR_FS/init"
chmod +x "$TMPDIR_FS/init"
echo "    OK"

# ── Pack cpio.gz ─────────────────────────────────────────────────────────────
echo "[6] Packing initramfs..."
cd "$TMPDIR_FS"
CPIO_BIN=$(which cpio 2>/dev/null || echo /bin/busybox)
if [ -x /bin/busybox ]; then
    find . | /bin/busybox cpio -H newc -o > "$BIN/hdgl_initrd.cpio" 2>/dev/null
else
    find . | cpio -H newc -o > "$BIN/hdgl_initrd.cpio" 2>/dev/null
fi
gzip -9 < "$BIN/hdgl_initrd.cpio" > "$BIN/hdgl_initrd.img"
rm "$BIN/hdgl_initrd.cpio"
cd "$SCRIPT_DIR"
echo "    OK ($(stat -c%s "$BIN/hdgl_initrd.img") bytes)"

# ── Embed in disk image ──────────────────────────────────────────────────────
echo "[7] Embedding in disk image..."
if [ -f "$BIN/hdgl_router64.img" ]; then
    # Ensure image is large enough
    CURRENT_SIZE=$(stat -c%s "$BIN/hdgl_router64.img")
    NEEDED=$((( 16896 + 4096 ) * 512))
    if [ "$CURRENT_SIZE" -lt "$NEEDED" ]; then
        truncate -s $((32 * 1024 * 1024)) "$BIN/hdgl_router64.img"
    fi
    dd if="$BIN/hdgl_initrd.img" of="$BIN/hdgl_router64.img" \
        bs=512 seek=16896 conv=notrunc 2>/dev/null
    echo "    OK (initrd at LBA 16896)"
else
    echo "    SKIP: run build.sh first to create bin/hdgl_router64.img"
fi

# ── Embed kernel if available ────────────────────────────────────────────────
echo "[8] Kernel..."
KERNEL=$(ls /boot/vmlinuz-* 2>/dev/null | sort -V | tail -1)
if [ -n "$KERNEL" ] && [ -f "$KERNEL" ]; then
    dd if="$KERNEL" of="$BIN/hdgl_router64.img" \
        bs=512 seek=512 conv=notrunc 2>/dev/null
    echo "    OK: $KERNEL embedded at LBA 512"
    echo ""
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo "  BOOT COMMAND (at Router64> prompt):"
    echo "    alpine 512 16896"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
else
    echo "    No kernel found at /boot/vmlinuz-*"
    echo "    Copy a bzImage manually:"
    echo "    dd if=your-bzImage of=bin/hdgl_router64.img bs=512 seek=512 conv=notrunc"
fi
