#!/bin/sh
# build_grub2_204.sh — Build GRUB2 2.04 with Ventoy modifications for hiperiso.
# ---------------------------------------------------------------------------
# hiperiso uses Ventoy as the GRUB substrate. This script unpacks the
# upstream GRUB2.04 source, overlays Ventoy's `grub2-modsrc` patch set,
# and builds the stock Ventoy GRUB binary. The rebranding layer (hiperiso
# kernel cmdline, JSON config, initramfs bridge) lives in
# `host/initramfs/` and the installed payload's `grub.cfg`, NOT in GRUB.
#
# The hiperiso source tree in `src/grub2/` is retained for reference but
# intentionally NOT compiled in here — it's an unfinished rebrand attempt
# that's blocked on partial modsrc/sed mismatches. The substrate approach
# is the supported path; the historical rebrand sources are kept only
# for context. See INTERFACES.sh (Build Architecture section) for the
# full rationale.
#
# Usage: scripts/build_grub2_204.sh
# Output: grub2/bin/BOOTX64.EFI, grub2/bin/grubx64_real.efi, grub2/bin/grubx64.efi
set -eu
(set -o pipefail) 2>/dev/null && set -o pipefail

HIPERISO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
DL_DIR="$HIPERISO_ROOT/build/downloads"
MODULE_TARBALL="$HIPERISO_ROOT/vendor/grub2-modsrc.tar.xz"
BUILD_DIR="$HIPERISO_ROOT/build/grub2-204"
SRC_DIR="$BUILD_DIR/SRC/grub-2.04"
PXE_DIR="$BUILD_DIR/PXE"
RUNTIME_GRUB_DIR="$BUILD_DIR/RUNTIME/grub"

rm -rf "$BUILD_DIR"
mkdir -p "$BUILD_DIR/SRC" "$PXE_DIR" "$RUNTIME_GRUB_DIR"

tar -xf "$DL_DIR/grub-2.04.tar.xz"      -C "$BUILD_DIR/SRC/"
tar -xf "$MODULE_TARBALL"              -C "$BUILD_DIR/SRC/"

find "$BUILD_DIR/SRC/grub-2.04/grub-core/ventoy" -type f \
     \( -name '*.c' -o -name '*.h' \) -exec sed -i \
     -e 's/(partition->len != 131072)/(partition->len != 65536)/g' \
     -e 's/(PartTbl\[1\]\.LastLBA + 1 - PartTbl\[1\]\.StartLBA) != 131072/(PartTbl[1].LastLBA + 1 - PartTbl[1].StartLBA) != 65536/g' \
     -e 's/PartTbl\[1\]\.SectorCount != 131072/PartTbl[1].SectorCount != 65536/g' \
     {} +

cp "$HIPERISO_ROOT/src/grub2/grub/grub.cfg" "$SRC_DIR/"

cd "$SRC_DIR"
make distclean 2>/dev/null || true
./autogen.sh
./configure --with-platform=efi --target=x86_64 \
    --prefix="$BUILD_DIR/INSTALL/" --disable-werror \
    CFLAGS="-std=gnu99 -Wno-error" HOST_CFLAGS="-std=gnu99 -Wno-error"
make -j"$(nproc)"

echo ">>> Installing GRUB tools and modules..."
make install 2>&1 | tail -5

INSTALL_DIR="$BUILD_DIR/INSTALL"
GRUB_LIB="$INSTALL_DIR/lib/grub/x86_64-efi"
EFI_OUTPUT_DIR="$HIPERISO_ROOT/grub2/bin"
EFI_OUTPUT="$EFI_OUTPUT_DIR/BOOTX64.EFI"
REAL_GRUB_OUTPUT="$EFI_OUTPUT_DIR/grubx64_real.efi"
GRUB_ALIAS_OUTPUT="$EFI_OUTPUT_DIR/grubx64.efi"
mkdir -p "$EFI_OUTPUT_DIR"

echo ">>> Building BOOTX64.EFI with Ventoy module..."

NET_MODULES="efinet net tftp http"
MODULES="file setkey blocklist ventoy test true regexp newc search \
at_keyboard usb_keyboard gcry_md5 hashsum gzio xzio lzopio \
ext2 xfs read halt sleep serial terminfo png password_pbkdf2 \
gcry_sha512 pbkdf2 part_gpt part_msdos ls tar squash4 loopback \
part_apple minicmd diskfilter linux relocator jpeg iso9660 udf \
hfsplus halt acpi mmap gfxmenu video_colors trig bitmap_scale \
gfxterm bitmap font fat exfat ntfs fshelp efifwsetup reboot echo \
configfile normal terminal gettext chain priority_queue bufio \
datetime cat extcmd crypto boot all_video efi_gop efi_uga \
video_bochs video_cirrus video video_fb gfxterm_background \
gfxterm_menu mouse fwload smbios zfs"
ALL_MODULES="$NET_MODULES $MODULES"

PATH="$INSTALL_DIR/bin:$INSTALL_DIR/sbin:$PATH" \
grub-mkimage \
    --directory "$GRUB_LIB" \
    --prefix '(,2)/grub' \
    --output "$EFI_OUTPUT" \
    --format 'x86_64-efi' \
    --compression 'auto' \
    $ALL_MODULES

grub-mknetdir \
    --directory="$GRUB_LIB" \
    --modules="$ALL_MODULES" \
    --net-directory="$PXE_DIR" \
    --subdir=grub2 \
    --locales=en@quot

rm -rf "$RUNTIME_GRUB_DIR/x86_64-efi"
mkdir -p "$RUNTIME_GRUB_DIR/x86_64-efi"

cp -a "$PXE_DIR/grub2/x86_64-efi/normal.mod" "$RUNTIME_GRUB_DIR/x86_64-efi/normal.mod"

ls -1 "$GRUB_LIB" | egrep '\.(lst|mod)$' | while read line; do
    modname="${line%.mod}"
    if ! echo " $ALL_MODULES " | grep -q " ${modname} "; then
        cp -a "$GRUB_LIB/$line" "$RUNTIME_GRUB_DIR/x86_64-efi/"
    fi
done

cp "$EFI_OUTPUT" "$REAL_GRUB_OUTPUT"
cp "$EFI_OUTPUT" "$GRUB_ALIAS_OUTPUT"

echo ">>> Built: $EFI_OUTPUT ($(du -h "$EFI_OUTPUT" | cut -f1))"
echo ">>> Copied: $REAL_GRUB_OUTPUT"
echo ">>> Copied: $GRUB_ALIAS_OUTPUT"
echo ">>> Verifying Ventoy module integrity..."
_VT=$(strings "$EFI_OUTPUT" | grep -c 'vt_' || true)
_VENTOY=$(strings "$EFI_OUTPUT" | grep -c 'ventoy_' || true)
echo "    vt_* symbols: $_VT"
echo "    ventoy_* symbols: $_VENTOY"
