#!/bin/bash
#
# build_ovmf.sh — Build OVMF UEFI firmware (EDK2) with SMM + Secure Boot
# ---------------------------------------------------------------------------
# Run from inside the EDK2 source tree (build/edk2).
# Produces a combined OVMF.fd (CODE+VARS) at:
#   Build/OvmfX64/RELEASE_GCC5/FV/OVMF.fd
#
set -euo pipefail

TOOLCHAIN="${TOOLCHAIN:-GCC5}"
TARGET="${TARGET:-RELEASE}"
ARCH="${ARCH:-X64}"
EDK2_DIR="${EDK2_DIR:-$(pwd)}"

[ -f OvmfPkg/build.sh ] || {
    echo "ERROR: not in EDK2 tree (OvmfPkg/build.sh missing) in $EDK2_DIR" >&2
    exit 1
}

echo "=== Building EDK2 BaseTools (C toolchain) ==="
# PCCTS parser code uses K&R-style function pointers (void (*)()) which
# modern GCC rejects with -Werror. Build with -Wno-error and gnu89.
make -C BaseTools/Source/C -j"$(nproc)" \
    CFLAGS="-MMD -MP -g -O2 -Wno-error -std=gnu89" \
    BUILD_CFLAGS="-MMD -MP -g -O2 -Wno-error -std=gnu89"

echo "=== Initializing EDK2 environment ==="
# shellcheck disable=SC1091
source edksetup.sh

echo "=== Building OVMF ($ARCH/$TARGET/$TOOLCHAIN, SMM + Secure Boot) ==="
OvmfPkg/build.sh \
    -a "$ARCH" \
    -b "$TARGET" \
    -t "$TOOLCHAIN" \
    -D SMM_REQUIRE=TRUE \
    -D SECURE_BOOT_ENABLE=TRUE

OVMF_FD="Build/OvmfX64/${TARGET}_${TOOLCHAIN}/FV/OVMF.fd"
if [ -f "$OVMF_FD" ]; then
    echo "=== OVMF firmware ready: $OVMF_FD ($(du -h "$OVMF_FD" | cut -f1)) ==="
else
    echo "ERROR: OVMF.fd not found at $OVMF_FD" >&2
    exit 1
fi
