# Shared helpers for all install scripts. Sourced, not executed.

set -euo pipefail

PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
TOOLS_DIR="$PROJECT_ROOT/tools"
DOWNLOAD_CACHE="$PROJECT_ROOT/.cache/downloads"

install -d "$TOOLS_DIR" "$DOWNLOAD_CACHE"

log() {
    printf '\033[1;34m[llvm816]\033[0m %s\n' "$*" >&2
}

warn() {
    printf '\033[1;33m[llvm816 WARN]\033[0m %s\n' "$*" >&2
}

die() {
    printf '\033[1;31m[llvm816 FAIL]\033[0m %s\n' "$*" >&2
    exit 1
}

# Download to cache unless already present. $1=url, $2=dest filename in cache.
fetchCached() {
    local url="$1"
    local name="$2"
    local dest="$DOWNLOAD_CACHE/$name"
    if [ -s "$dest" ]; then
        log "cached: $name"
    else
        log "fetching: $url"
        curl -fL --retry 3 --progress-bar -o "$dest.part" "$url"
        mv "$dest.part" "$dest"
    fi
    printf '%s\n' "$dest"
}

needCmd() {
    command -v "$1" >/dev/null 2>&1 || die "required command not found: $1"
}

haveCmd() {
    command -v "$1" >/dev/null 2>&1
}

# runGnoMameSmoke <omf-path> <marker1> [<marker2> ...]
#
# Launch an already-built GNO/ME OMF under real GS/OS 6.0.4 + GNO in
# headless MAME and assert that every <marker> matches.  Each marker is
# a single `addr=hexValue` token in the runInGno.sh `--check` syntax
# (e.g. `0x025000=C0DE`).  Multiple markers are passed positionally —
# the function does NOT split on commas, so a caller wanting two checks
# passes two separate args.
#
# Exit 0 on all-match, 1 on any miss.  Mirrors tests/lua/runLuaTest.sh's
# pattern of "run program in emulator, then assert canned markers";
# scoped at GNO instead of bare-metal because the C++ smoke / cxxstdlib
# / cursor work needs a real OMF Loader path.
#
# Required prereqs (caller should pre-check or let this function die):
#   tools/cadius/cadius
#   tools/gsos/6.0.4 - System.Disk.po
#   tools/gno/gnobase.po
runGnoMameSmoke() {
    local omfPath="$1"
    shift
    [ -f "$omfPath" ] || die "runGnoMameSmoke: OMF not found: $omfPath"
    [ $# -ge 1 ]      || die "runGnoMameSmoke: at least one marker required"
    local args=()
    local m
    for m in "$@"; do
        args+=("$m")
    done
    bash "$PROJECT_ROOT/scripts/runInGno.sh" "$omfPath" --check "${args[@]}"
}
