#!/bin/sh
# =============================================================================
#  vxcli universal installer  —  Linux & macOS
#
#  Usage (the line you publish on vxcloud.io/download/cli):
#     curl -fsSL https://vxcloud.io/download/cli/install.sh | sh
#
#  Options (environment variables):
#     VXCLI_VERSION=19.8.9      install a specific version (default: latest)
#     VXCLI_INSTALL_DIR=/path   install location (default: $HOME/.local/bin)
#     VXCLI_BASE_URL=http://... override download host (for local testing)
#
#  No sudo needed: defaults to a per-user bin dir. Verifies sha256 before
#  installing. POSIX sh — works under sh, bash, zsh, dash, ash.
# =============================================================================
set -eu

BASE_URL="${VXCLI_BASE_URL:-https://vxcloud.io/download/cli}"
INSTALL_DIR="${VXCLI_INSTALL_DIR:-$HOME/.local/bin}"
BIN_NAME="vxcli"

# ── pretty logging (falls back to plain if not a tty) ──
if [ -t 1 ]; then
    B='\033[0;34m'; G='\033[0;32m'; Y='\033[1;33m'; R='\033[0;31m'; N='\033[0m'
else
    B=''; G=''; Y=''; R=''; N=''
fi
info()  { printf "${B}==>${N} %s\n" "$1"; }
ok()    { printf "${G} ok ${N} %s\n" "$1"; }
warn()  { printf "${Y}warn${N} %s\n" "$1"; }
die()   { printf "${R}error${N} %s\n" "$1" >&2; exit 1; }

# ── need a downloader: dl = url->file, dlo = url->stdout ──
if command -v curl >/dev/null 2>&1; then
    dl()  { curl -fsSL "$1" -o "$2"; }
    dlo() { curl -fsSL "$1"; }
elif command -v wget >/dev/null 2>&1; then
    dl()  { wget -qO "$2" "$1"; }
    dlo() { wget -qO- "$1"; }
else
    die "need curl or wget installed"
fi

# ── detect OS ──
OS="$(uname -s)"
case "$OS" in
    Linux)  OS="linux" ;;
    Darwin) OS="darwin" ;;
    *)      die "unsupported OS: $OS (this installer covers Linux and macOS; on Windows use install.ps1)" ;;
esac

# ── detect ARCH ──
ARCH="$(uname -m)"
case "$ARCH" in
    x86_64|amd64)        ARCH="amd64" ;;
    aarch64|arm64)       ARCH="arm64" ;;
    *)                   die "unsupported architecture: $ARCH (we ship amd64 and arm64)" ;;
esac

# ── resolve version ──
VERSION="${VXCLI_VERSION:-}"
if [ -z "$VERSION" ]; then
    info "Resolving latest version..."
    VERSION="$(dlo "$BASE_URL/stable.txt" | tr -d ' \t\r\n')"
    [ -n "$VERSION" ] || die "could not read latest version from $BASE_URL/stable.txt"
fi
info "Installing vxcli v$VERSION for ${OS}/${ARCH}"

ASSET="vxcli_${VERSION}_${OS}_${ARCH}"
ASSET_URL="$BASE_URL/v$VERSION/$ASSET"
SUMS_URL="$BASE_URL/v$VERSION/checksums.txt"

# ── download to a temp dir we clean up ──
TMP="$(mktemp -d 2>/dev/null || mktemp -d -t vxcli)"
trap 'rm -rf "$TMP"' EXIT INT TERM

info "Downloading $ASSET ..."
dl "$ASSET_URL" "$TMP/$BIN_NAME" || die "download failed: $ASSET_URL"

# ── verify sha256 against checksums.txt ──
if dl "$SUMS_URL" "$TMP/checksums.txt" 2>/dev/null; then
    # Match the row for $ASSET regardless of sha256sum mode: text "<hash>  name"
    # or binary "<hash> *name" (the leading '*' is stripped before comparing).
    EXPECTED="$(awk -v a="$ASSET" '{f=$NF; sub(/^[*]/,"",f); if (f==a) print $1}' "$TMP/checksums.txt" 2>/dev/null)"
    if [ -n "$EXPECTED" ]; then
        if command -v sha256sum >/dev/null 2>&1; then
            ACTUAL="$(sha256sum "$TMP/$BIN_NAME" | awk '{print $1}')"
        elif command -v shasum >/dev/null 2>&1; then
            ACTUAL="$(shasum -a 256 "$TMP/$BIN_NAME" | awk '{print $1}')"
        else
            ACTUAL=""; warn "no sha256 tool found — skipping checksum verification"
        fi
        if [ -n "$ACTUAL" ]; then
            [ "$ACTUAL" = "$EXPECTED" ] || die "checksum mismatch! expected $EXPECTED got $ACTUAL"
            ok "Checksum verified"
        fi
    else
        warn "no checksum entry for $ASSET — skipping verification"
    fi
else
    warn "checksums.txt unavailable — skipping verification"
fi

# ── install ──
mkdir -p "$INSTALL_DIR" || die "cannot create $INSTALL_DIR"
chmod 0755 "$TMP/$BIN_NAME"
mv -f "$TMP/$BIN_NAME" "$INSTALL_DIR/$BIN_NAME" 2>/dev/null \
    || die "cannot write to $INSTALL_DIR (set VXCLI_INSTALL_DIR to a writable path, or re-run with sudo)"
ok "Installed to $INSTALL_DIR/$BIN_NAME"

# ── PATH guidance ──
case ":$PATH:" in
    *":$INSTALL_DIR:"*) IN_PATH=1 ;;
    *)                  IN_PATH=0 ;;
esac
if [ "$IN_PATH" = "0" ]; then
    warn "$INSTALL_DIR is not on your PATH."
    SHELL_RC=""
    case "${SHELL:-}" in
        *zsh)  SHELL_RC="$HOME/.zshrc" ;;
        *bash) SHELL_RC="$HOME/.bashrc" ;;
    esac
    printf "      Add it with:\n"
    printf "        export PATH=\"%s:\$PATH\"\n" "$INSTALL_DIR"
    if [ -n "$SHELL_RC" ]; then
        printf "      To make it permanent:\n"
        printf "        echo 'export PATH=\"%s:\$PATH\"' >> %s && exec \$SHELL\n" "$INSTALL_DIR" "$SHELL_RC"
    fi
fi

echo ""
ok "vxcli v$VERSION installed. Run:  vxcli version"
echo "   (if 'vxcli' is not found, open a new terminal or fix PATH as shown above)"
