#!/usr/bin/env bash
# Sanity-check every installed tool. Exits non-zero if anything is missing.

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

fails=0

check() {
    local label="$1"; shift
    if "$@" >/dev/null 2>&1; then
        printf '  [ OK ]  %s\n' "$label"
    else
        printf '  [FAIL]  %s  (%s)\n' "$label" "$*"
        fails=$((fails + 1))
    fi
}

log "verifying toolchain"

# Build tools
check "cmake"          cmake --version
check "ninja"          ninja --version
check "clang (host)"   clang --version
check "git"            git --version

# llvm-mos source + SDK
check "llvm-mos source tree"   test -d "$TOOLS_DIR/llvm-mos/.git"
check "llvm-mos-sdk extracted" test -x "$TOOLS_DIR/llvm-mos-sdk/bin/mos-common-clang"

# MAME + ROMs
check "mame binary"                 command -v mame
check "mame Lua console support"    bash -c "mame -showusage 2>&1 | grep -q -- '-console'"
check "rom: apple2gs.zip"           test -s "$TOOLS_DIR/mame/roms/apple2gs.zip"
check "rom: apple2gsr1.zip"         test -s "$TOOLS_DIR/mame/roms/apple2gsr1.zip"

# Calypsi benchmark
check "calypsi cc65816"   test -x "$TOOLS_DIR/calypsi/bin/cc65816"

# ORCA/C reference
check "orca-c source"   test -d "$TOOLS_DIR/orca-c/.git"

echo
if [ "$fails" -eq 0 ]; then
    log "all checks passed"
    exit 0
else
    die "$fails check(s) failed"
fi
