# 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
}
