#!/bin/bash
# Build Memtest86+ (AArch64 EFI) from sources/mt86plus_*zip
# Output: ../bin/utils/mt86plus.efi  (paths relative to this script)

set -e

CWD=$(cd "$(dirname "$0")" && pwd)
OUTDIR=$CWD/../bin/utils

# Newest source zip if more than one is present.
SRCZIP=$(ls -1 $CWD/sources/mt86plus_*zip 2>/dev/null | sort -V | tail -n1)
[ -z "$SRCZIP" ] && { echo "No sources/mt86plus_*zip found in $CWD" ; exit 1 ; }
echo "Source: $SRCZIP"

TMP=$(mktemp -d /tmp/mt86plus-build.XXXXXX)
trap 'rm -rf "$TMP"' EXIT

unzip -q "$SRCZIP" -d "$TMP"

# Don't assume the zip's top-level directory name.
BUILDDIR=$(find "$TMP" -type d -path '*/build/aarch64' | head -n1)
[ -z "$BUILDDIR" ] && { echo "build/aarch64 not found in $SRCZIP" ; exit 1 ; }

# GIT=none: release zip has no .git. The Makefile uses native gcc on aarch64
# and sets its own freestanding CFLAGS - don't inject SLKCFLAGS.
make -C "$BUILDDIR" -j$(nproc) GIT=none || exit 1

# Not stripped: mt86plus is a raw objcopy -O binary PE image with no symbol
# table to remove, and running strip on it risks corrupting the PE layout.
file "$BUILDDIR/mt86plus" | grep -q 'EFI' || { echo "Output is not an EFI image" ; exit 1 ; }

mkdir -p "$OUTDIR"
install -m 0755 "$BUILDDIR/mt86plus" "$OUTDIR/mt86plus.efi"
echo "Installed: $(cd "$OUTDIR" && pwd)/mt86plus.efi"
