#!/bin/sh
# shellcheck shell=dash

set -u

APP_NAME="altertable"
BASE_URL="https://github.com/altertable-ai/altertable-cli/releases/latest/download"
INSTALL_DIR="$HOME/.local/bin"

detect_platform() {
  OS="$(uname -s)"
  ARCH="$(uname -m)"

  case "$OS" in
    Linux)  os="linux" ;;
    Darwin) os="darwin" ;;
    *)
      echo "❌ Unsupported operating system: $OS"
      exit 1
      ;;
  esac

  case "$ARCH" in
    x86_64|amd64)  arch="x64" ;;
    aarch64|arm64) arch="arm64" ;;
    *)
      echo "❌ Unsupported architecture: $ARCH"
      exit 1
      ;;
  esac

  echo "${os}-${arch}"
}

PLATFORM="$(detect_platform)"
DOWNLOAD_URL="${BASE_URL}/altertable-${PLATFORM}"

echo "Installing Altertable CLI for ${PLATFORM}..."
mkdir -p "$INSTALL_DIR"

if ! output="$(curl -LsSf "$DOWNLOAD_URL" -o "$INSTALL_DIR/$APP_NAME" 2>&1)"; then
  echo "❌ Failed to download $APP_NAME for ${PLATFORM}"
  echo "$output"
  exit 1
fi

chmod +x "$INSTALL_DIR/$APP_NAME"

printf "\n🎉 Altertable CLI installed successfully!\n"
printf "\nTo use it, add this directory to your PATH: \`export PATH=\"%s:\$PATH\"\`\n" "$INSTALL_DIR"
printf "\nRun \`altertable --help\` to see available commands.\n"
printf "\nNeed help? See https://altertable.ai/docs\n"
