#!/usr/bin/env bash
# verify-iigs-all.sh - Boot-verify EVERY launchable example on the built
# joey.2mg (the S16 apps cadius packed onto the volume), each via verify-iigs.sh
# with its per-example distinct-color threshold. Reports one line per example
# and exits nonzero if any example fails to render.
#
# Requires: toolchains/env.sh sourced; build/iigs/bin/joey.2mg built
# (`make iigs-disk`); apple2gs ROM + gsos-system.po (see verify-iigs.sh).
set -uo pipefail

repo=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
source "$repo/toolchains/env.sh" 2>/dev/null || true
: "${LLVM816_ROOT:?source toolchains/env.sh first}"
CADIUS="${CADIUS:-$LLVM816_ROOT/tools/cadius/cadius}"
disk="$repo/build/iigs/bin/joey.2mg"

[ -f "$disk" ]   || { echo "verify-iigs-all: $disk missing (run 'make iigs-disk')" >&2; exit 2; }
[ -x "$CADIUS" ] || { echo "verify-iigs-all: cadius not found at $CADIUS" >&2; exit 2; }

# Launchable examples = ProDOS type S16 files in the catalog, lowercased.
apps=$("$CADIUS" CATALOG "$disk" 2>/dev/null | awk '$2 == "S16" { print tolower($1) }' | sort)
[ -n "$apps" ] || { echo "verify-iigs-all: no S16 apps found on $disk" >&2; exit 2; }

echo "verify-iigs-all: booting $(echo "$apps" | wc -w) examples off joey.2mg"
fails=0
for ex in $apps; do
    out=$("$repo/scripts/verify-iigs.sh" "$ex" 2>&1)
    rc=$?
    info=$(echo "$out" | grep -oE 'distinctNibbles=[0-9]+ nonZeroBytes=[0-9]+' | tail -1)
    if [ "$rc" -eq 0 ]; then
        echo "  PASS  $ex ($info)"
    else
        echo "  FAIL  $ex ($info)"
        fails=$((fails + 1))
    fi
done

echo "verify-iigs-all: $fails failed"
[ "$fails" -eq 0 ]
