#!/bin/sh
# -----------------------------------------------------------------------------
# TokenBot CLI installer (thin wrapper)
#
# This is a thin wrapper around `npm install -g tokenbot` for users who want a
# single-line install. A single-binary distribution (no Node.js prerequisite) is
# planned -- track Wave 5 of the CLI-first rearchitecture rollout.
# TODO(wave-5): link the roadmap issue here once the public roadmap is up.
#
# This script is intentionally minimal:
#   - Detects platform (macOS / Linux), prints a hint and exits on others.
#   - Verifies `npm` is on PATH; if not, prints a friendly Node.js install hint.
#   - Verifies Node.js >= 22 (the `tokenbot` package requires it).
#   - Runs `npm install -g tokenbot`. Uses `sudo` if a global install would
#     otherwise be rejected for permissions, and only when stdin is a TTY.
#
# Hosted at https://install.tokenbot.com (CloudFront distribution
# E18ZC9ZLXHYSF7 routes that host to /install/install.sh in the
# tokenbot-landing S3 bucket via the install-subdomain-router CloudFront
# Function -- see infra/RUNBOOK-install-subdomain.md).
#
# Usage:
#   curl -fsSL https://install.tokenbot.com | sh
# -----------------------------------------------------------------------------

set -eu

NODE_MIN_MAJOR=22
NODE_URL="https://nodejs.org/"
PKG="tokenbot"

color() {
    # $1 = color code, $2 = text
    if [ -t 1 ]; then
        printf '\033[%sm%s\033[0m\n' "$1" "$2"
    else
        printf '%s\n' "$2"
    fi
}

info()  { color "1;34" "==> $1"; }
warn()  { color "1;33" "==> $1"; }
err()   { color "1;31" "==> $1" >&2; }
ok()    { color "1;32" "==> $1"; }

detect_platform() {
    uname_s=$(uname -s 2>/dev/null || echo unknown)
    case "$uname_s" in
        Darwin) echo "macos" ;;
        Linux)  echo "linux" ;;
        *)      echo "unsupported" ;;
    esac
}

require_npm() {
    if ! command -v npm >/dev/null 2>&1; then
        err "npm is not installed."
        err ""
        err "TokenBot requires Node.js >= ${NODE_MIN_MAJOR}. Install Node.js first:"
        err "    ${NODE_URL}"
        err ""
        err "On macOS:  brew install node"
        err "On Linux:  see your distro's package manager, or use https://github.com/nvm-sh/nvm"
        exit 1
    fi
}

require_node_version() {
    node_v=$(node --version 2>/dev/null || echo "v0.0.0")
    major=$(echo "$node_v" | sed 's/^v//' | cut -d. -f1)
    if [ -z "$major" ] || [ "$major" -lt "$NODE_MIN_MAJOR" ] 2>/dev/null; then
        err "Node.js ${node_v} is too old. TokenBot requires Node.js >= ${NODE_MIN_MAJOR}."
        err "Upgrade Node.js: ${NODE_URL}"
        exit 1
    fi
}

install_pkg() {
    info "Installing ${PKG} globally via npm..."
    if npm install -g "$PKG"; then
        ok "Installed ${PKG}. Run 'tokenbot init' to get started."
        return 0
    fi

    # Permissions failure is common with system Node installs. Retry with sudo
    # only if we have a TTY (i.e., the user can answer a password prompt).
    if [ -t 0 ] && command -v sudo >/dev/null 2>&1; then
        warn "npm install failed (likely a permissions issue). Retrying with sudo..."
        if sudo npm install -g "$PKG"; then
            ok "Installed ${PKG}. Run 'tokenbot init' to get started."
            return 0
        fi
    fi

    err "Failed to install ${PKG}. See the npm error above."
    err "If this is a permissions issue, consider using a Node version manager"
    err "such as nvm (https://github.com/nvm-sh/nvm) so global installs don't"
    err "require sudo."
    exit 1
}

main() {
    plat=$(detect_platform)
    if [ "$plat" = "unsupported" ]; then
        err "Unsupported platform: $(uname -s 2>/dev/null || echo unknown)."
        err "Try installing directly with: npm install -g ${PKG}"
        exit 1
    fi
    info "Detected platform: ${plat}"

    require_npm
    require_node_version
    install_pkg
}

main "$@"
