#!/bin/sh
# fetch-vendor.sh — download proprietary vendor utilities into iso/vendor.
#
# Usage:
#   STORCLI_URL=... STORCLI_SHA256=... \
#   SAS2IRCU_URL=... SAS2IRCU_SHA256=... \
#   SAS3IRCU_URL=... SAS3IRCU_SHA256=... \
#   MSTFLINT_URL=... MSTFLINT_SHA256=... \
#   sh scripts/fetch-vendor.sh

set -eu

ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
OUT_DIR="$ROOT_DIR/iso/vendor"
mkdir -p "$OUT_DIR"

need_cmd() {
    command -v "$1" >/dev/null 2>&1 || { echo "ERROR: required command not found: $1" >&2; exit 1; }
}

need_cmd sha256sum

download_to() {
    url="$1"
    out="$2"
    if command -v wget >/dev/null 2>&1; then
        wget -O "$out" "$url"
        return 0
    fi
    if command -v curl >/dev/null 2>&1; then
        curl -fsSL "$url" -o "$out"
        return 0
    fi
    echo "ERROR: required command not found: wget or curl" >&2
    exit 1
}

fetch_one() {
    name="$1"
    url="$2"
    sha="$3"

    if [ -z "$url" ] || [ -z "$sha" ]; then
        echo "[vendor] skip $name (URL/SHA not provided)"
        return 0
    fi

    dst="$OUT_DIR/$name"
    tmp="$dst.tmp"

    echo "[vendor] downloading $name"
    download_to "$url" "$tmp"

    got=$(sha256sum "$tmp" | awk '{print $1}')
    want=$(echo "$sha" | tr '[:upper:]' '[:lower:]')
    if [ "$got" != "$want" ]; then
        rm -f "$tmp"
        echo "ERROR: checksum mismatch for $name" >&2
        echo "  got:  $got" >&2
        echo "  want: $want" >&2
        exit 1
    fi

    mv "$tmp" "$dst"
    chmod +x "$dst" || true
    echo "[vendor] ok: $name"
}

fetch_one "storcli64" "${STORCLI_URL:-}" "${STORCLI_SHA256:-}"
fetch_one "sas2ircu" "${SAS2IRCU_URL:-}" "${SAS2IRCU_SHA256:-}"
fetch_one "sas3ircu" "${SAS3IRCU_URL:-}" "${SAS3IRCU_SHA256:-}"
fetch_one "mstflint" "${MSTFLINT_URL:-}" "${MSTFLINT_SHA256:-}"

echo "[vendor] done. output dir: $OUT_DIR"
