#!/bin/sh
# Arbitor CLI installer
# Usage: curl -fsSL https://get.arbitor.dev/install.sh | sh
#
# Environment variables:
#   ARBITOR_VERSION     - Pin a specific version (e.g., "0.1.0"), default: latest
#   ARBITOR_INSTALL_DIR - Custom install directory, default: /usr/local/bin
#   NO_COLOR            - Disable colored output

set -eu

# --- Configuration ---

GITHUB_REPO="inquori/arbitor"
DEFAULT_INSTALL_DIR="/usr/local/bin"

# --- Color output ---

setup_colors() {
    if [ -t 1 ] && [ -z "${NO_COLOR-}" ]; then
        RED='\033[0;31m'
        GREEN='\033[0;32m'
        BOLD='\033[1m'
        RESET='\033[0m'
    else
        RED=''
        GREEN=''
        BOLD=''
        RESET=''
    fi
}

# --- Logging ---

info() {
    printf "${GREEN}%s${RESET}\n" "$*"
}

error() {
    printf "${RED}error: %s${RESET}\n" "$*" >&2
}

bold() {
    printf "${BOLD}%s${RESET}\n" "$*"
}

# --- Platform detection ---

detect_os() {
    os="$(uname -s)"
    case "$os" in
        Linux)  echo "linux" ;;
        Darwin) echo "darwin" ;;
        *)
            error "Unsupported operating system: $os"
            error "Arbitor supports Linux and macOS."
            exit 1
            ;;
    esac
}

detect_arch() {
    arch="$(uname -m)"
    case "$arch" in
        x86_64)          echo "amd64" ;;
        aarch64|arm64)   echo "arm64" ;;
        *)
            error "Unsupported architecture: $arch"
            error "Arbitor supports amd64 and arm64."
            exit 1
            ;;
    esac
}

# --- Download helpers ---

has_cmd() {
    command -v "$1" >/dev/null 2>&1
}

download() {
    url="$1"
    dest="$2"
    if has_cmd curl; then
        curl -fsSL -o "$dest" "$url"
    elif has_cmd wget; then
        wget -qO "$dest" "$url"
    else
        error "Either curl or wget is required to download arbitor."
        error "Install one and try again."
        exit 1
    fi
}

download_stdout() {
    url="$1"
    if has_cmd curl; then
        curl -fsSL "$url"
    elif has_cmd wget; then
        wget -qO- "$url"
    else
        error "Either curl or wget is required to download arbitor."
        error "Install one and try again."
        exit 1
    fi
}

# --- Version resolution ---

resolve_version() {
    if [ -n "${ARBITOR_VERSION-}" ]; then
        # Strip leading 'v' if present
        echo "$ARBITOR_VERSION" | sed 's/^v//'
        return
    fi

    api_url="https://api.github.com/repos/${GITHUB_REPO}/releases/latest"
    tag="$(download_stdout "$api_url" | grep '"tag_name"' | sed 's/.*"tag_name": *"v\{0,1\}\([^"]*\)".*/\1/')"

    if [ -z "$tag" ]; then
        error "Could not determine latest version from GitHub."
        error "Set ARBITOR_VERSION to install a specific version."
        exit 1
    fi

    echo "$tag"
}

# --- Main ---

main() {
    setup_colors

    os="$(detect_os)"
    arch="$(detect_arch)"
    info "Detected: ${os} ${arch}"

    version="$(resolve_version)"
    bold "Downloading arbitor v${version}..."

    tarball_url="https://github.com/${GITHUB_REPO}/releases/download/v${version}/arbitor_${os}_${arch}.tar.gz"
    install_dir="${ARBITOR_INSTALL_DIR:-$DEFAULT_INSTALL_DIR}"

    # Create temp directory with cleanup trap
    tmp_dir="$(mktemp -d)"
    trap 'rm -rf "$tmp_dir"' EXIT

    # Download
    tarball_path="${tmp_dir}/arbitor.tar.gz"
    download "$tarball_url" "$tarball_path" || {
        error "Download failed."
        error "URL: ${tarball_url}"
        error "Check that version v${version} exists and includes a release for ${os}/${arch}."
        exit 1
    }

    # Extract
    tar xzf "$tarball_path" -C "$tmp_dir" || {
        error "Failed to extract tarball."
        exit 1
    }

    if [ ! -f "${tmp_dir}/arbitor" ]; then
        error "Expected binary 'arbitor' not found in tarball."
        exit 1
    fi

    # Install
    info "Installing to ${install_dir}/arbitor..."

    if [ -w "$install_dir" ]; then
        cp "${tmp_dir}/arbitor" "${install_dir}/arbitor"
        chmod +x "${install_dir}/arbitor"
    else
        echo "Elevated permissions required to install to ${install_dir}."
        sudo cp "${tmp_dir}/arbitor" "${install_dir}/arbitor"
        sudo chmod +x "${install_dir}/arbitor"
    fi

    # Verify
    if [ -x "${install_dir}/arbitor" ]; then
        installed_version="$("${install_dir}/arbitor" --version 2>/dev/null || true)"
        if [ -n "$installed_version" ]; then
            info "arbitor ${installed_version} installed successfully"
        else
            info "arbitor v${version} installed to ${install_dir}/arbitor"
        fi
    else
        error "Installation failed: binary not executable at ${install_dir}/arbitor"
        exit 1
    fi
}

main
