#!/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"

# 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

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}"

DOWNLOAD_URL="${BASE_URL}/tm-latest-${OS}-${ARCH}"
VERSIONS_DIR="$HOME/.local/lib/tachyon/versions"
SYMLINK="$HOME/.local/bin/tm"

mkdir -p "$VERSIONS_DIR" "$(dirname "$SYMLINK")"

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

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 'tm license <your-license-key>' to activate."
else
    echo ""
    echo "Installed successfully. Make sure ~/.local/bin is in your PATH."
fi
