#!/usr/bin/env bash
# =============================================================================
# Mac-specific iPXE build shortcut
#
# Builds the native tg3 EFI binary and an SNP fallback, packages each into
# a bootable FAT32 .img with autoexec.ipxe alongside the EFI binary.
#
# Usage:
#   ./build-mac.sh [OPTIONS]
#
# Options:
#   -s, --script <file>   autoexec script (default: boot.ipxe if present)
#   -j, --jobs   <n>      Parallel jobs (default: nproc)
#   -h, --help
# =============================================================================
set -euo pipefail

SCRIPT_DIR="$(dirname "$0")"
JOBS="$(nproc 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null || echo 4)"
SCRIPT=""

# ── Colour helpers ─────────────────────────────────────────────────────────────
if [ -t 1 ]; then
    C_BOLD='\033[1m'; C_GREEN='\033[0;32m'; C_CYAN='\033[0;36m'
    C_RED='\033[0;31m'; C_RESET='\033[0m'
else
    C_BOLD=''; C_GREEN=''; C_CYAN=''; C_RED=''; C_RESET=''
fi
info() { echo -e "${C_CYAN}▶${C_RESET} $*"; }
ok()   { echo -e "${C_GREEN}✔${C_RESET} $*"; }
die()  { echo -e "${C_RED}✘${C_RESET} $*" >&2; exit 1; }

while [[ $# -gt 0 ]]; do
    case $1 in
        -s|--script) SCRIPT="$2"; shift 2 ;;
        -j|--jobs)   JOBS="$2";   shift 2 ;;
        -h|--help)   sed -n '3,13p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;;
        *) die "Unknown option: $1" ;;
    esac
done

# Auto-detect boot.ipxe in repo root
if [[ -z "$SCRIPT" && -f "$SCRIPT_DIR/boot.ipxe" ]]; then
    SCRIPT="$SCRIPT_DIR/boot.ipxe"
    info "Auto-detected script: $SCRIPT"
fi

SCRIPT_OPT=""
[[ -n "$SCRIPT" ]] && SCRIPT_OPT="--script $SCRIPT"

# ── Build matrix ──────────────────────────────────────────────────────────────
#
#  ipxe-x64.img    — native tg3 driver (try first on Intel Macs)
#  snponly-x64.img — SNP fallback      (if tg3 probe fails)
#
echo -e "${C_BOLD}Mac iPXE build${C_RESET}"
echo ""

info "1/2  Native tg3 (efi-x64)…"
bash "$SCRIPT_DIR/build.sh" -p efi-x64 -j "$JOBS" --image $SCRIPT_OPT
echo ""

info "2/2  SNP fallback (snp-x64)…"
bash "$SCRIPT_DIR/build.sh" -p snp-x64 -j "$JOBS" --image $SCRIPT_OPT
echo ""

# ── Summary ───────────────────────────────────────────────────────────────────
BUILD_DIR="$SCRIPT_DIR/build"
echo -e "${C_BOLD}Output:${C_RESET}"
for f in "$BUILD_DIR"/*.img; do
    size=$(du -h "$f" | cut -f1)
    ok "  $size  $(basename "$f")"
done

echo ""
echo -e "${C_BOLD}Flash to USB (replace sdX):${C_RESET}"
echo "  sudo dd if=$BUILD_DIR/ipxe-x64.img of=/dev/sdX bs=4M status=progress"
echo ""
echo -e "${C_BOLD}On Mac:${C_RESET}"
echo "  Hold Option key at boot → select USB"
echo "  If NIC not found, reflash with snponly-x64.img"
