#!/bin/bash
#
# Tachyon Manager (tm) installer
#
# Usage:
#   curl -fsSL https://verify.tachyonpress.com/public/install.sh | bash
#

set -e

BASE_URL="https://verify.tachyonpress.com/public"
VERSIONS_DIR="/usr/local/lib/tachyon/versions"
SYMLINK="/usr/local/bin/tm"

# Detect OS and architecture
OS=$(uname -s | tr '[:upper:]' '[:lower:]')
ARCH=$(uname -m)

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

case "$OS" in
    linux|darwin) ;;
    *)
        echo "Error: Unsupported OS: $OS"
        exit 1
        ;;
esac

# Check for root/sudo
if [ "$(id -u)" -ne 0 ]; then
    echo "Error: This script requires root privileges."
    echo "Run: curl -fsSL ${BASE_URL}/install.sh | sudo bash"
    exit 1
fi

echo "Installing tm for ${OS}/${ARCH}..."

# Get latest version
VERSION=$(curl -fsSL "${BASE_URL}/tm-latest-version" 2>/dev/null)
if [ -z "$VERSION" ]; then
    echo "Error: Could not determine latest version"
    exit 1
fi

echo "  Version: ${VERSION}"

# Create directories
mkdir -p "$VERSIONS_DIR"

# Download binary
BINARY_NAME="tm-${VERSION}-${OS}-${ARCH}"
BINARY_PATH="${VERSIONS_DIR}/${BINARY_NAME}"
DOWNLOAD_URL="${BASE_URL}/tm-latest-${OS}-${ARCH}"

echo "  Downloading..."
curl -fsSL -o "$BINARY_PATH" "$DOWNLOAD_URL"
chmod 755 "$BINARY_PATH"

# Create symlink
REL_PATH="../lib/tachyon/versions/${BINARY_NAME}"
rm -f "$SYMLINK"
ln -s "$REL_PATH" "$SYMLINK"

echo "  Installed: ${SYMLINK} → ${REL_PATH}"

# Verify
if command -v tm &>/dev/null; then
    echo ""
    tm version
    echo ""
    echo "Run 'sudo tm license <your-license-key>' to activate."
else
    echo ""
    echo "Installed successfully. Make sure /usr/local/bin is in your PATH."
fi
