#!/bin/bash
set -e

INSTALL_DIR="/usr/local/bin"

# Detect OS and architecture
OS=$(uname -s | tr '[:upper:]' '[:lower:]')
ARCH=$(uname -m)
case $ARCH in
  x86_64) ARCH="x64" ;;
  aarch64|arm64) ARCH="arm64" ;;
  *)
    echo "Unsupported architecture: $ARCH"
    exit 1
    ;;
esac

PLATFORM="${OS}-${ARCH}"
BINARY_NAME="anycloud-${PLATFORM}"

# Version: use env var or "stable"
VERSION=${ANYCLOUD_VERSION:-"stable"}

# Get tarball URL from npm registry
if [ "$VERSION" = "latest" ] || [ "$VERSION" = "stable" ]; then
  TARBALL_URL=$(curl -fsSL "https://registry.npmjs.org/anycloud/${VERSION}" | grep -o '"tarball":"[^"]*"' | cut -d'"' -f4)
  if [ -z "$TARBALL_URL" ]; then
    echo "Error: Failed to fetch latest version from npm registry"
    exit 1
  fi
else
  TARBALL_URL="https://registry.npmjs.org/anycloud/-/anycloud-${VERSION}.tgz"
fi

echo "Downloading anycloud ${VERSION} for ${PLATFORM}..."

# Download tarball and extract binary
if ! curl -fsSL "$TARBALL_URL" 2>/tmp/curl-error.log | tar -xzf - --strip-components=2 -C /tmp "package/binaries/${BINARY_NAME}" 2>/tmp/tar-error.log; then
  echo "Error: Failed to download or extract anycloud ${VERSION}"
  echo "Please verify the version exists: https://www.npmjs.com/package/anycloud?activeTab=versions"
  rm -f /tmp/curl-error.log /tmp/tar-error.log 2>/dev/null || true
  exit 1
fi
rm -f /tmp/curl-error.log /tmp/tar-error.log 2>/dev/null || true
mv /tmp/${BINARY_NAME} /tmp/anycloud
chmod +x /tmp/anycloud

# Install to INSTALL_DIR (may need sudo)
if [ -w "$INSTALL_DIR" ]; then
  mv /tmp/anycloud "$INSTALL_DIR/anycloud"
else
  echo "Installing to $INSTALL_DIR (requires sudo)..."
  sudo mv /tmp/anycloud "$INSTALL_DIR/anycloud"
fi

echo ""
echo "anycloud installed successfully to $INSTALL_DIR/anycloud"
echo ""
anycloud --version
