#!/bin/bash
set -e

# --- STEP 1: Check for Prerequisites ---
if ! command -v xxd &> /dev/null || ! command -v gcc &> /dev/null; then
    echo "Error: 'xxd' and 'gcc' are required to build the bootloader."
    exit 1
fi
if [ ! -f kernel/bzImage ] || [ ! -f initramfs.cpio.gz ]; then
    echo "Error: Missing kernel/initramfs files. Run 'make_kernel_images.sh' first."
    exit 1
fi

echo "--- Building HDGL Bootloader ---"

# 1. Convert kernel/initramfs to C arrays
xxd -i kernel/bzImage > kernel.h
xxd -i initramfs.cpio.gz > initramfs.h

# 2. Compile the bootloader as a raw binary
x86_64-linux-gnu-gcc \
    -ffreestanding \
    -O2 \
    -nostdlib \
    -I. \
    hdgl_bootloader.c \
    -o hdgl_bootloader.bin

echo "Bootloader build complete: hdgl_bootloader.bin"

echo "--- Building Kernel Module ---"
# 3. Build the Linux Kernel Module (requires kernel headers for current system)
make -f Makefile

echo "Kernel module build complete: hdgl_lattice_sysfs.ko"
echo "Package build SUCCESS."