#!/bin/sh
# Axior Verify installer — detects platform and installs the correct binary.
# Usage: curl -fsSL https://install.axior.dev | sh
#
# Environment variables:
#   AXIOR_INSTALL_DIR  — installation directory (default: ~/.local/bin or /usr/local/bin)
#   AXIOR_VERSION      — specific version to install (default: latest)
#   AXIOR_NO_VERIFY    — skip SHA256 verification (not recommended)

set -e

CDN_BASE="https://install.axior.dev"
BINARY="axior"

# Colors (respects NO_COLOR)
if [ -z "${NO_COLOR:-}" ] && [ -t 1 ]; then
    BOLD='\033[1m'
    BLUE='\033[34m'
    GREEN='\033[32m'
    RED='\033[31m'
    DIM='\033[2m'
    RESET='\033[0m'
else
    BOLD='' BLUE='' GREEN='' RED='' DIM='' RESET=''
fi

info() { printf "${BLUE}${BOLD}info${RESET} %s\n" "$1"; }
success() { printf "${GREEN}${BOLD}  ✓${RESET} %s\n" "$1"; }
error() { printf "${RED}${BOLD}error${RESET} %s\n" "$1" >&2; }

# Detect platform
detect_platform() {
    OS="$(uname -s | tr '[:upper:]' '[:lower:]')"
    ARCH="$(uname -m)"

    case "$OS" in
        linux) PLATFORM="linux" ;;
        darwin) PLATFORM="darwin" ;;
        *) error "Unsupported OS: $OS"; exit 1 ;;
    esac

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

    if [ "$PLATFORM" = "linux" ] && [ "$ARCH" = "aarch64" ]; then
        error "Linux ARM64 binaries are not yet available."
        info "Install via pip instead: pip install axior-verify"
        exit 1
    fi
}

# Get latest version from GitHub
get_version() {
    if [ -n "${AXIOR_VERSION:-}" ]; then
        VERSION="$AXIOR_VERSION"
        return
    fi

    VERSION=$(curl -fsSL "${CDN_BASE}/latest/version.txt")

    if [ -z "$VERSION" ]; then
        error "Could not determine latest version"
        exit 1
    fi
}

# Determine install directory
get_install_dir() {
    if [ -n "${AXIOR_INSTALL_DIR:-}" ]; then
        INSTALL_DIR="$AXIOR_INSTALL_DIR"
    elif [ -d "$HOME/.local/bin" ] || [ "$(id -u)" != "0" ]; then
        INSTALL_DIR="$HOME/.local/bin"
    else
        INSTALL_DIR="/usr/local/bin"
    fi
    mkdir -p "$INSTALL_DIR"
}

# Verify SHA256 checksum
verify_checksum() {
    EXPECTED_HASH="$1"
    FILE="$2"

    if command -v sha256sum >/dev/null 2>&1; then
        ACTUAL_HASH=$(sha256sum "$FILE" | cut -d' ' -f1)
    elif command -v shasum >/dev/null 2>&1; then
        ACTUAL_HASH=$(shasum -a 256 "$FILE" | cut -d' ' -f1)
    else
        info "No sha256sum or shasum found, skipping verification"
        return 0
    fi

    if [ "$ACTUAL_HASH" != "$EXPECTED_HASH" ]; then
        error "SHA256 mismatch!"
        error "  Expected: $EXPECTED_HASH"
        error "  Actual:   $ACTUAL_HASH"
        error "  The downloaded file may be corrupted or tampered with."
        rm -f "$FILE"
        exit 1
    fi

    success "SHA256 verified"
}

# Download and install
install() {
    FILENAME="${BINARY}-${VERSION}-${PLATFORM}-${ARCH}"
    BINARY_URL="${CDN_BASE}/v${VERSION}/${FILENAME}"
    CHECKSUMS_URL="${CDN_BASE}/v${VERSION}/checksums-sha256.txt"
    DEST="${INSTALL_DIR}/${BINARY}"

    info "Installing axior v${VERSION} (${PLATFORM}/${ARCH})"

    TEMP=$(mktemp)
    trap 'rm -f "$TEMP" "$TEMP.checksums"' EXIT

    if ! curl -fsSL "$BINARY_URL" -o "$TEMP"; then
        error "Download failed: $BINARY_URL"
        error "Check ${CDN_BASE} for available binaries"
        exit 1
    fi

    # Verify checksum unless explicitly skipped
    if [ -z "${AXIOR_NO_VERIFY:-}" ]; then
        info "Verifying checksum..."
        if curl -fsSL "$CHECKSUMS_URL" -o "$TEMP.checksums" 2>/dev/null; then
            EXPECTED=$(grep "$FILENAME" "$TEMP.checksums" | cut -d' ' -f1)
            if [ -n "$EXPECTED" ]; then
                verify_checksum "$EXPECTED" "$TEMP"
            else
                info "Binary not found in checksums file, skipping verification"
            fi
        else
            info "Checksums file not available, skipping verification"
        fi
    fi

    chmod +x "$TEMP"
    mv "$TEMP" "$DEST"

    success "Installed to ${DEST}"
}

# Verify installation
verify() {
    if command -v "$BINARY" >/dev/null 2>&1; then
        success "$("$BINARY" --version)"
    elif [ -x "${INSTALL_DIR}/${BINARY}" ]; then
        success "$("${INSTALL_DIR}/${BINARY}" --version)"
        if ! echo "$PATH" | grep -q "$INSTALL_DIR"; then
            printf "\n${DIM}  Add to PATH: export PATH=\"%s:\$PATH\"${RESET}\n" "$INSTALL_DIR"
        fi
    fi
}

main() {
    printf "\n${BOLD}${BLUE} ◆ Axior Verify Installer${RESET}\n\n"

    detect_platform
    get_version
    get_install_dir
    install
    verify

    printf "\n${DIM}  Run 'axior doctor' to verify your setup.${RESET}\n\n"
}

main
