#!/bin/bash
# Filename: claude-code-install.sh
# Description: Installs or updates the Claude Code CLI tool from GCS releases.

set -eou pipefail

GCS_BUCKET="https://storage.googleapis.com/claude-code-dist-86c565f3-f756-42ad-8dfa-d59b1c096819/claude-code-releases"
INSTALL_PATH="/usr/local/bin/claude"

# Check OS
case "$(uname -s)" in
    Linux) ;;
    *) echo "Unsupported OS: $(uname -s)" >&2; exit 1 ;;
esac

# Detect arch
case "$(uname -m)" in
    x86_64|amd64) platform="linux-x64" ;;
    arm64|aarch64) platform="linux-arm64" ;;
    *) echo "Unsupported architecture: $(uname -m)" >&2; exit 1 ;;
esac

# Fetch latest version string from GCS
latest=$(wget -qO- "$GCS_BUCKET/latest")

# Check if already installed and up to date
if command -v claude >/dev/null 2>&1; then
    current=$(claude --version 2>/dev/null | grep -oE '[0-9]+\.[0-9]+\.[0-9]+[^ ]*' | head -1 || true)
    if [ "$current" = "$latest" ]; then
        echo "Claude $current is already up to date."
        exit 0
    elif [ -n "$current" ]; then
        echo "Upgrading Claude $current -> $latest"
    fi
else
    echo "Installing Claude $latest"
fi

# Fetch manifest and extract checksum
manifest=$(wget -qO- "$GCS_BUCKET/$latest/manifest.json")
checksum=$(echo "$manifest" | grep -A5 "\"$platform\"" | grep '"checksum"' | grep -oE '[a-f0-9]{64}')

if [ -z "$checksum" ] || [[ ! "$checksum" =~ ^[a-f0-9]{64}$ ]]; then
    echo "Could not extract checksum for $platform from manifest" >&2
    exit 1
fi

# Download binary to a temp file
tmp=$(mktemp)
trap 'rm -f "$tmp"' EXIT

echo "Downloading..."
if ! wget -qO "$tmp" "$GCS_BUCKET/$latest/$platform/claude"; then
    echo "Download failed" >&2
    exit 1
fi

# Verify checksum
actual=$(sha256sum "$tmp" | cut -d' ' -f1)
if [ "$actual" != "$checksum" ]; then
    echo "Checksum verification failed" >&2
    exit 1
fi

chmod 755 "$tmp"
mv "$tmp" "$INSTALL_PATH"

echo "Claude $latest installed to $INSTALL_PATH"
