#!/usr/bin/env sh
# HiTechCloud CLI Installer
# Usage: curl -fsSL https://get-mcp.hitechcloud.vn/cli | sh

set -e

echo "=== HiTechCloud Agent CLI Installer ==="
OS="$(uname -s | tr '[:upper:]' '[:lower:]')"
ARCH="$(uname -m)"

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

INSTALL_DIR="/usr/local/bin"
BINARY_NAME="hitechcloud"

echo "Detected OS: $OS, Architecture: $ARCH"
echo "Downloading HiTechCloud CLI binary..."

DOWNLOAD_URL="https://get-mcp.hitechcloud.vn/cli/download/${OS}/${ARCH}"

if [ -w "$INSTALL_DIR" ]; then
  curl -fsSL "$DOWNLOAD_URL" -o "${INSTALL_DIR}/${BINARY_NAME}" || {
    echo "Direct binary download not available on preview, copying local binary if present..."
    cp -f /home/HiTechCloud_Agent_Platform/target/release/hitechcloud "${INSTALL_DIR}/${BINARY_NAME}" 2>/dev/null || true
  }
  chmod +x "${INSTALL_DIR}/${BINARY_NAME}" 2>/dev/null || true
else
  sudo curl -fsSL "$DOWNLOAD_URL" -o "${INSTALL_DIR}/${BINARY_NAME}" 2>/dev/null || {
    sudo cp -f /home/HiTechCloud_Agent_Platform/target/release/hitechcloud "${INSTALL_DIR}/${BINARY_NAME}" 2>/dev/null || true
  }
  sudo chmod +x "${INSTALL_DIR}/${BINARY_NAME}" 2>/dev/null || true
fi

echo "HiTechCloud CLI installed successfully to ${INSTALL_DIR}/${BINARY_NAME}!"
echo "Run 'hitechcloud --help' to get started."
