#!/bin/bash
#
# build_all.sh — Master build orchestrator for hiperiso
# ---------------------------------------------------------------------------
# Runs the full pipeline:
#   1. download sources
#   2. build host kernel (KVM built-in)         -> staging/vmlinuz
#   3. build stripped QEMU                      -> staging/qemu-system-x86_64
#   4. build OVMF firmware (SMM + Secure Boot)  -> staging/OVMF.fd
#   5. build GRUB2 with hiperiso module         -> staging/BOOTX64.EFI
#   6. build busybox (static)                   -> staging/busybox
#   7. build hiperiso-log tool                  -> staging/hiperiso-log
#   8. pack initramfs                           -> staging/initramfs.cpio.gz
#   9. build GUI/tool payload                   -> build/payload/
#  10. assemble final distributable payload     -> build/payload/
#
# Usage:  ./build_all.sh [build_dir]
#         SKIP_DOWNLOAD=1 ./build_all.sh         # skip re-downloading
#
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
BUILD_DIR="${1:-$REPO_ROOT/build}"
STAGING="$BUILD_DIR/staging"
PAYLOAD="$BUILD_DIR/payload"
JOBS="${JOBS:-$(nproc)}"

mkdir -p "$STAGING/efi" "$STAGING/initramfs"

step() { printf '\n\033[1;34m=== [%d/%d] %s ===\033[0m\n' "$1" "$2" "$3"; }

# ── 1. Download sources ─────────────────────────────────────────────────────
if [ "${SKIP_DOWNLOAD:-0}" != "1" ]; then
    step 1 10 "Downloading sources"
    "$SCRIPT_DIR/download_sources.sh" "$BUILD_DIR"
else
    step 1 10 "Skipping download (SKIP_DOWNLOAD=1)"
fi

# ── 2. Build host kernel ────────────────────────────────────────────────────
step 2 10 "Building host kernel (KVM built-in)"
(
    cd "$BUILD_DIR/linux"
    cp "$REPO_ROOT/host/kernel/hiperiso_defconfig" .config
    make olddefconfig
    sed -i 's/^KBUILD_CFLAGS := -m\$(BITS) -O2/KBUILD_CFLAGS := -m$(BITS) -O2 -std=gnu11/' arch/x86/boot/compressed/Makefile
    make -j"$JOBS" bzImage
    cp arch/x86/boot/bzImage "$STAGING/efi/vmlinuz"
)
echo "  [ok] $(du -h "$STAGING/efi/vmlinuz" | cut -f1) vmlinuz"

# ── 3. Build QEMU ───────────────────────────────────────────────────────────
step 3 10 "Building stripped QEMU"
(
    cd "$BUILD_DIR/qemu"
    "$SCRIPT_DIR/configure_qemu.sh"
    make -j"$JOBS" qemu-system-x86_64
    cp build/qemu-system-x86_64 "$STAGING/qemu-system-x86_64"
    strip "$STAGING/qemu-system-x86_64" || true
)

# ── 4. Build OVMF firmware ──────────────────────────────────────────────────
step 4 10 "Acquiring OVMF firmware"
if [ -d "$BUILD_DIR/edk2" ] && command -v nasm >/dev/null 2>&1 && command -v iasl >/dev/null 2>&1; then
    (
        cd "$BUILD_DIR/edk2"
        bash "$REPO_ROOT/firmware/build_ovmf.sh" && \
        cp Build/OvmfX64/RELEASE_GCC5/FV/OVMF.fd "$STAGING/OVMF.fd"
    ) || {
        echo "  [warn] EDK2 build failed, falling back to system OVMF"
        cp /usr/share/edk2/x64/OVMF.4m.fd "$STAGING/OVMF.fd" 2>/dev/null || \
        cp /usr/share/OVMF/OVMF.fd "$STAGING/OVMF.fd" 2>/dev/null || \
        { echo "ERROR: No OVMF available"; exit 1; }
    }
elif [ -f /usr/share/edk2/x64/OVMF.4m.fd ]; then
    cp /usr/share/edk2/x64/OVMF.4m.fd "$STAGING/OVMF.fd"
    echo "  [ok] using system pre-built OVMF"
elif [ -f /usr/share/OVMF/OVMF.fd ]; then
    cp /usr/share/OVMF/OVMF.fd "$STAGING/OVMF.fd"
    echo "  [ok] using system pre-built OVMF"
else
    echo "ERROR: No OVMF available (install edk2-ovmf or build from source)"
    exit 1
fi

# ── 5. Build GRUB2 (with full hiperiso module) ──────────────────────────────
step 5 10 "Building GRUB2 with hiperiso module"
if [ -f "$SCRIPT_DIR/build_grub2_204.sh" ]; then
    bash "$SCRIPT_DIR/build_grub2_204.sh"
    cp "$REPO_ROOT/grub2/bin/BOOTX64.EFI" "$STAGING/efi/BOOTX64.EFI"
    [ -f "$REPO_ROOT/grub2/bin/grubx64_real.efi" ] && cp "$REPO_ROOT/grub2/bin/grubx64_real.efi" "$STAGING/efi/grubx64_real.efi"
    [ -f "$REPO_ROOT/grub2/bin/grubx64.efi" ] && cp "$REPO_ROOT/grub2/bin/grubx64.efi" "$STAGING/efi/grubx64.efi"
    echo "  [ok] $(du -h "$STAGING/efi/BOOTX64.EFI" | cut -f1) BOOTX64.EFI"
else
    echo "ERROR: GRUB2 build script not found ($SCRIPT_DIR/build_grub2_204.sh)"
    exit 1
fi

# ── 6. Build busybox (static binary for initramfs) ──────────────────────────
step 6 10 "Building busybox (static)"
(
    cd "$BUILD_DIR/busybox"
    yes "" | make defconfig >/dev/null 2>&1 || [ $? -eq 141 ]
    sed -i 's/# CONFIG_STATIC is not set/CONFIG_STATIC=y/' .config
    yes "" | make oldconfig >/dev/null 2>&1 || [ $? -eq 141 ]
    sed -i 's/^CONFIG_TC=.*/# CONFIG_TC is not set/' .config
    make -j"$JOBS"
    cp busybox "$STAGING/busybox"
)
echo "  [ok] $(du -h "$STAGING/busybox" | cut -f1) busybox"

# ── 7. Build hiperiso-log ───────────────────────────────────────────────────
step 7 10 "Building hiperiso-log tool"
if [ -f "$REPO_ROOT/logging/hiperiso-log/Makefile" ]; then
    ( cd "$REPO_ROOT/logging/hiperiso-log" && make )
    cp "$REPO_ROOT/logging/hiperiso-log/hiperiso-log" "$STAGING/hiperiso-log"
else
    echo "  [warn] hiperiso-log Makefile not present — skipping (log tool task)"
fi

# ── 8. Pack initramfs ───────────────────────────────────────────────────────
step 8 10 "Packing initramfs"
"$SCRIPT_DIR/build_initramfs.sh" "$STAGING"

# ── 9. Build GUI/tool payload ───────────────────────────────────────────────
step 9 10 "Building GUI and installer tools"
sh "$SCRIPT_DIR/build_gui_all.sh"

# ── 10. Assemble final distributable payload ────────────────────────────────
step 10 10 "Assembling final payload"
bash "$SCRIPT_DIR/package_release.sh"

printf '\n\033[1;32m=== hiperiso build complete ===\033[0m\n'
echo "Payload: $PAYLOAD"
echo "Run GUI: $PAYLOAD/Hiperiso.sh"
echo "Install CLI: sudo bash $PAYLOAD/Hiperiso2Disk.sh -I /dev/sdX   (GPT default, Secure Boot OFF)"
echo "  -I   fresh install   -u   update existing   -m   use MBR   -s   enable Secure Boot"
