#!/bin/sh
# hyperai installer - detects OS/arch, downloads the matching release archive,
# verifies its SHA-256, and installs the binary to $HOME/.local/bin.
#
# Usage:
#   curl -fsSL https://cli.hyperfx.ai/install | sh
#
# Overrides:
#   PREFIX   install prefix (default: $HOME/.local; binary goes in $PREFIX/bin)
#   VERSION  specific release tag, e.g. v0.2.0 (default: latest)
#   HYPERAI_INSTALL_BASE_URL  override the release host for testing
set -eu

BASE_URL="${HYPERAI_INSTALL_BASE_URL:-https://cli.hyperfx.ai}"
PREFIX="${PREFIX:-$HOME/.local}"
BIN_DIR="$PREFIX/bin"
VERSION="${VERSION:-latest}"

err() { echo "x $*" >&2; exit 1; }

detect_os() {
  case "$(uname -s)" in
    Darwin) echo macOS ;;
    Linux)  echo linux ;;
    *)      err "unsupported OS: $(uname -s). See $BASE_URL for manual downloads" ;;
  esac
}

detect_arch() {
  case "$(uname -m)" in
    x86_64|amd64) echo x86_64 ;;
    arm64|aarch64) echo arm64 ;;
    *) err "unsupported arch: $(uname -m)" ;;
  esac
}

need() { command -v "$1" >/dev/null 2>&1 || err "missing required tool: $1"; }
need curl
need tar

if command -v shasum >/dev/null 2>&1; then
  checksum_cmd() { shasum -a 256 -c - >/dev/null; }
elif command -v sha256sum >/dev/null 2>&1; then
  checksum_cmd() { sha256sum -c - >/dev/null; }
else
  err "missing required tool: shasum or sha256sum"
fi

OS="$(detect_os)"
ARCH="$(detect_arch)"

if [ "$VERSION" = "latest" ]; then
  VERSION="$(curl -fsSL "$BASE_URL/releases/latest" \
    | grep -o '"tag_name": *"[^"]*"' | head -n1 | cut -d'"' -f4)"
  [ -n "$VERSION" ] || err "could not resolve latest version"
fi

ASSET="hyperai_${VERSION#v}_${OS}_${ARCH}.tar.gz"
URL="$BASE_URL/releases/download/$VERSION/$ASSET"
SUMS_URL="$BASE_URL/releases/download/$VERSION/checksums.txt"

TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT

echo "-> downloading $ASSET ($VERSION)"
curl -fSL -o "$TMP/$ASSET" "$URL" \
  || err "download failed. Not every release includes $OS/$ARCH - see $BASE_URL"
curl -fSL -o "$TMP/checksums.txt" "$SUMS_URL"

echo "-> verifying checksum"
( cd "$TMP" && grep " $ASSET\$" checksums.txt | checksum_cmd ) \
  || err "checksum verification failed"

echo "-> extracting"
tar -xzf "$TMP/$ASSET" -C "$TMP"

mkdir -p "$BIN_DIR"
TARGET="$BIN_DIR/hyperai"
if [ -x "$TARGET" ]; then
  CURRENT_VERSION="$("$TARGET" --version 2>/dev/null || true)"
  echo "existing: ${CURRENT_VERSION:-unknown}"
fi
install -m 0755 "$TMP/hyperai" "$TARGET"
echo "installed $TARGET"

case ":$PATH:" in
  *":$BIN_DIR:"*) ;;
  *)
    echo ""
    echo "$BIN_DIR is not on \$PATH. Add this to your shell rc:"
    echo "  export PATH=\"$BIN_DIR:\$PATH\""
    ;;
esac

"$TARGET" --version
echo "Run 'hyperai update' for future updates."
echo "Run 'hyperai uninstall' to remove the CLI. Config is preserved by default."
