#!/usr/bin/env bash
# verify-iigs-save.sh - Runtime gate for the IIgs save-file HAL's GS/OS calls
# (Create $2001 for the SAVES/ directory, Volume $2008 for jlDiskFree). Boots
# GS/OS under MAME, launches the SAVE example off a freshly built JOEYLIB disk,
# and reads two spots out of the Super Hi-Res framebuffer:
#   - the save lamp at (32,94): color 3 (COLOR_SAVE_OK) means jlSaveWrite
#     succeeded, i.e. jlpSaveDirEnsure (GS/OS Create) + the write into SAVES/
#     both worked; color 4 means it failed.
#   - the disk-free bar row at y=137: any COLOR_BAR_FILL (6) pixels mean
#     jlDiskFree() (GS/OS Volume) returned a nonzero free-byte count.
# PASS requires lamp==3 AND barFill>0.
#
# Set JOEY_SAVE_NOPRESTAGE=1 to build the disk WITHOUT prestaging SAVES/, which
# isolates GS/OS Create: a green lamp then proves Create made the directory
# from scratch (not that a prestaged one was merely present).
#
# Requires: toolchains/env.sh sourced; build/iigs/bin/SAVE + DRAW built; the
# apple2gs ROM and gsos-system.po present (same as verify-iigs.sh).
set -euo pipefail

repo=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
source "$repo/toolchains/env.sh" 2>/dev/null || true
: "${LLVM816_ROOT:?source toolchains/env.sh first}"

sys_disk=$repo/toolchains/emulators/support/gsos-system.po
rompath="${MAME_ROMPATH:-$HOME/.mame/roms}"
readFrame="${MAME_READ_FRAME:-9000}"

[ -f "$repo/build/iigs/bin/SAVE" ] || { echo "verify-iigs-save: build/iigs/bin/SAVE missing (make iigs first)" >&2; exit 2; }
[ -f "$sys_disk" ] || { echo "verify-iigs-save: missing $sys_disk" >&2; exit 2; }

work=$(mktemp -d -t joeylib-vsave.XXXXXX)
trap 'rm -rf "$work"' EXIT

# Build the data disk with SAVE (DRAW keeps a known-good sibling on the volume).
# JOEY_SAVE_NOPRESTAGE=1 omits the prestaged SAVES/, isolating GS/OS Create.
prestage_env=""
if [ -n "${JOEY_SAVE_NOPRESTAGE:-}" ]; then
    prestage_env="JOEY_SKIP_SAVES_PRESTAGE=1"
    echo "verify-iigs-save: building WITHOUT prestaged SAVES/ (isolating GS/OS Create)"
fi
env $prestage_env JOEY_DISK_EXAMPLES="SAVE DRAW" "$repo/scripts/make-iigs-disk.sh" "$work/joey.2mg" >/dev/null
cp "$sys_disk" "$work/boot.po"

cat > "$work/vsave.lua" <<LUA
local cpu = manager.machine.devices[":maincpu"]
local mem = cpu.spaces["program"]
local nat = manager.machine.natkeyboard
local frame = 0
local idx = 1

local function field(port, name)
    local p = manager.machine.ioport.ports[port]
    if p == nil then return nil end
    return p.fields[name]
end
local key_cmd = field(":macadb:KEY3", "Command / Open Apple")
local function press(f)   if f then f:set_value(1) end end
local function release(f) if f then f:set_value(0) end end

local function nib(x, y)
    local b = mem:read_u8(0xE12000 + y * 160 + (x >> 1))
    if (x & 1) == 0 then return (b >> 4) & 0x0F else return b & 0x0F end
end

local function report()
    local lamp = nib(32, 94)          -- COLOR_SAVE_OK=3 / COLOR_SAVE_FAIL=4
    local barFill = 0
    for x = 12, 291 do                -- bar row; COLOR_BAR_FILL=6
        if nib(x, 137) == 6 then barFill = barFill + 1 end
    end
    io.write(string.format("VERIFY-SAVE lamp=%d barFill=%d\n", lamp, barFill))
    io.flush()
end

local steps = {
    {3000, function() nat:post("J") end},
    {3120, function() press(key_cmd) end},
    {3126, function() nat:post("o") end},
    {3180, function() release(key_cmd) end},
    {3540, function() nat:post("SAVE") end},
    {3660, function() press(key_cmd) end},
    {3666, function() nat:post("o") end},
    {3720, function() release(key_cmd) end},
    {$readFrame, function() report(); manager.machine:exit() end},
}

emu.register_frame_done(function()
    frame = frame + 1
    while idx <= #steps and frame >= steps[idx][1] do
        steps[idx][2]()
        idx = idx + 1
    end
end)
LUA

cd "$work"
out=$(QT_QPA_PLATFORM=offscreen SDL_VIDEODRIVER=dummy SDL_AUDIODRIVER=dummy \
    timeout 300 mame apple2gs \
        -rompath "$rompath" \
        -flop3 "$work/boot.po" -flop4 "$work/joey.2mg" \
        -video none -sound none -nothrottle \
        -autoboot_script "$work/vsave.lua" </dev/null 2>&1) || true

line=$(echo "$out" | grep -E '^VERIFY-SAVE ' | tail -1)
echo "$line"
if [ -z "$line" ]; then
    echo "verify-iigs-save: FAIL - no report (boot/launch failed)" >&2
    echo "$out" | tail -15 >&2
    exit 1
fi
lamp=$(echo "$line" | sed -E 's/.*lamp=([0-9]+).*/\1/')
barFill=$(echo "$line" | sed -E 's/.*barFill=([0-9]+).*/\1/')
if [ "$lamp" = "3" ] && [ "$barFill" -gt 0 ]; then
    echo "verify-iigs-save: PASS (save OK lamp + disk-free bar; GS/OS Create+Volume work)"
else
    echo "verify-iigs-save: FAIL (lamp=$lamp expected 3, barFill=$barFill expected >0)" >&2
    exit 1
fi
