#!/usr/bin/env bash
# Install MAME (via apt) and fetch Apple IIgs ROM sets into the project-local
# rompath. Self-contained — MAME is launched with -rompath to point here, so
# this does not touch the user's ~/.mame directory.

set -euo pipefail
source "$(dirname "$0")/common.sh"

MAME_ROMS="$TOOLS_DIR/mame/roms"
ROM_BASE="https://archive.org/download/mame-0.240-roms-split_202201/MAME%200.240%20ROMs%20(split)"

install -d "$MAME_ROMS"

# 1. MAME binary via apt. Ubuntu noble ships 0.264.
if ! haveCmd mame; then
    log "installing mame"
    sudo apt-get install -y --no-install-recommends mame mame-tools
else
    log "mame already installed: $(mame -version 2>/dev/null | head -1 || true)"
fi

# 2. ROM sets. apple2gs is current ROM 03; apple2gsr1 is ROM 01 (many 1986-era
#    titles require this variant). Pull both so we can test against either.
for romName in apple2gs.zip apple2gsr1.zip; do
    dest="$MAME_ROMS/$romName"
    if [ -s "$dest" ]; then
        log "rom already present: $romName"
        continue
    fi
    log "downloading $romName"
    curl -fL --retry 3 --progress-bar \
        -o "$dest.part" "$ROM_BASE/$romName"
    mv "$dest.part" "$dest"
done

# 3. Quick Lua capability check — we rely on -console for the test harness.
if mame -showusage 2>&1 | grep -q -- '-console'; then
    log "mame Lua console available"
else
    warn "mame binary does not appear to support -console / Lua scripting"
fi

log "mame install done"
log "  binary:    $(command -v mame)"
log "  rompath:   $MAME_ROMS"
log "  launch:    mame -rompath $MAME_ROMS apple2gs"
