#!/bin/sh
set -e

# Go-Claw One-line Installer
# Usage: curl -fsSL https://goclaw.ulab.mn/install.sh | sh

# 1. Colors & Output Formatting
RED='\033[0;31m'
GREEN='\033[0;32m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

info() {
    printf "${BLUE}==>${NC} %s\n" "$1"
}

success() {
    printf "${GREEN}==>${NC} %s\n" "$1"
}

error() {
    printf "${RED}Error:${NC} %s\n" "$1" >&2
}

# 2. Determine base URL silently (Fallback to Firebase Hosting if custom domain is not ready)
BASE_URL="https://goclaw.ulab.mn"
if ! curl -sfI -m 5 "$BASE_URL/releases/latest.json" >/dev/null 2>&1; then
    BASE_URL="https://goclaw-hosting.web.app"
fi

# 3. Detect Operating System and Architecture
OS="$(uname -s)"
ARCH="$(uname -m)"

case "$OS" in
    Darwin)
        TARGET_OS="darwin"
        ;;
    Linux)
        TARGET_OS="linux"
        ;;
    *)
        error "Unsupported operating system: $OS"
        exit 1
        ;;
esac

case "$ARCH" in
    x86_64|amd64)
        TARGET_ARCH="amd64"
        ;;
    arm64|aarch64)
        TARGET_ARCH="arm64"
        ;;
    armv7l|armv7|armhf)
        TARGET_ARCH="armv7"
        ;;
    *)
        error "Unsupported architecture: $ARCH"
        exit 1
        ;;
esac

# Validate support for target combination
if [ "$TARGET_OS" = "darwin" ] && [ "$TARGET_ARCH" = "armv7" ]; then
    error "Unsupported combination: macOS on armv7"
    exit 1
fi

ASSET_NAME="goclaw-${TARGET_OS}-${TARGET_ARCH}"

info "Detected platform: $TARGET_OS / $TARGET_ARCH"
info "Downloading latest release..."

# 4. Fetch latest release information
LATEST_JSON=$(curl -fsSL "$BASE_URL/releases/latest.json")
VERSION=$(echo "$LATEST_JSON" | grep -o '"version":"[^"]*' | grep -o '[^"]*$')

if [ -z "$VERSION" ]; then
    error "Failed to parse latest version from $BASE_URL/releases/latest.json"
    exit 1
fi

# 5. Create temporary directory for download
TMP_DIR=$(mktemp -d)
clean_up() {
    rm -rf "$TMP_DIR"
}
trap clean_up EXIT

# 6. Download binary and checksums
curl -fsSL "$BASE_URL/releases/${VERSION}/${ASSET_NAME}" -o "${TMP_DIR}/${ASSET_NAME}"
curl -fsSL "$BASE_URL/releases/${VERSION}/checksums.json" -o "${TMP_DIR}/checksums.json"

# 7. Verify Checksum
EXPECTED_SHA=$(grep -o "\"${ASSET_NAME}\"[[:space:]]*:[[:space:]]*\"[^\"]*" "${TMP_DIR}/checksums.json" | grep -o '[^"]*$')

if [ -z "$EXPECTED_SHA" ]; then
    error "No checksum found for $ASSET_NAME in checksums.json"
    exit 1
fi

calculate_sha256() {
    if command -v sha256sum >/dev/null 2>&1; then
        sha256sum "$1" | awk '{print $1}'
    elif command -v shasum >/dev/null 2>&1; then
        shasum -a 256 "$1" | awk '{print $1}'
    elif command -v openssl >/dev/null 2>&1; then
        openssl dgst -sha256 "$1" | awk '{print $2}'
    else
        echo ""
    fi
}

ACTUAL_SHA=$(calculate_sha256 "${TMP_DIR}/${ASSET_NAME}")

if [ -n "$ACTUAL_SHA" ] && [ "$ACTUAL_SHA" != "$EXPECTED_SHA" ]; then
    error "Checksum mismatch! Expected: $EXPECTED_SHA, Got: $ACTUAL_SHA"
    exit 1
fi

# 8. Install to /usr/local/bin
INSTALL_DIR="/usr/local/bin"
BINARY_PATH="${INSTALL_DIR}/goclaw"

USE_SUDO=""
if [ ! -w "$INSTALL_DIR" ]; then
    info "Requesting sudo permissions to install to ${INSTALL_DIR}..."
    USE_SUDO="sudo"
fi

$USE_SUDO cp "${TMP_DIR}/${ASSET_NAME}" "$BINARY_PATH"
$USE_SUDO chmod +x "$BINARY_PATH"

success "Go-Claw installed successfully to ${BINARY_PATH}!"

# 9. Verify Installation & Path
case ":$PATH:" in
    *:"$INSTALL_DIR":*)
        # Verify execution
        if command -v goclaw >/dev/null 2>&1; then
            goclaw version || true
        fi
        ;;
    *)
        info "${RED}Warning:${NC} ${INSTALL_DIR} is not in your PATH. You may need to add it to your shell configuration."
        info "To run goclaw, use the full path: ${BINARY_PATH}"
        ;;
esac
