#!/bin/sh
set -eu

# ULTRV CLI installer
# Usage: curl -fsSL https://dl.ultrv.com/install.sh | sh

INSTALL_DIR="/usr/local/bin"
BASE_URL="https://dl.ultrv.com/cli/latest"

detect_target() {
  os=$(uname -s)
  arch=$(uname -m)

  case "$os" in
    Linux)
      case "$arch" in
        x86_64)  echo "x86_64-unknown-linux-gnu" ;;
        aarch64) echo "aarch64-unknown-linux-gnu" ;;
        arm64)   echo "aarch64-unknown-linux-gnu" ;;
        *) echo "Error: unsupported architecture: $arch" >&2; exit 1 ;;
      esac
      ;;
    Darwin)
      case "$arch" in
        x86_64)  echo "x86_64-apple-darwin" ;;
        arm64)   echo "aarch64-apple-darwin" ;;
        aarch64) echo "aarch64-apple-darwin" ;;
        *) echo "Error: unsupported architecture: $arch" >&2; exit 1 ;;
      esac
      ;;
    *)
      echo "Error: unsupported OS: $os" >&2
      echo "For Windows, download from https://dl.ultrv.com/cli/latest/ultrv-x86_64-pc-windows-msvc.zip" >&2
      exit 1
      ;;
  esac
}

main() {
  target=$(detect_target)
  url="${BASE_URL}/ultrv-${target}.tar.gz"

  echo "Installing ultrv for ${target}..."

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

  if command -v curl >/dev/null 2>&1; then
    curl -fsSL "$url" -o "$tmpdir/ultrv.tar.gz"
  elif command -v wget >/dev/null 2>&1; then
    wget -qO "$tmpdir/ultrv.tar.gz" "$url"
  else
    echo "Error: curl or wget required" >&2
    exit 1
  fi

  tar xzf "$tmpdir/ultrv.tar.gz" -C "$tmpdir"

  if [ -w "$INSTALL_DIR" ]; then
    mv "$tmpdir/ultrv" "$INSTALL_DIR/ultrv"
  else
    echo "Installing to ${INSTALL_DIR} (requires sudo)..."
    sudo mv "$tmpdir/ultrv" "$INSTALL_DIR/ultrv"
  fi

  chmod +x "$INSTALL_DIR/ultrv"

  echo "ultrv installed to ${INSTALL_DIR}/ultrv"
  echo "Run 'ultrv' to get started."
}

main
