#!/usr/bin/env bash
# 注册 Nexus 全局 CLI（/usr/local/bin）— install / upgrade / nx 均会调用
#
#   NEXUS_ROOT=/opt/nexus bash deploy/install-nx-cli.sh
#
set -euo pipefail

NEXUS_ROOT="${NEXUS_ROOT:-/opt/nexus}"
BIN_DIR="${NEXUS_BIN_DIR:-/usr/local/bin}"
DEPLOY="${NEXUS_ROOT}/deploy"

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

info()  { echo -e "${GREEN}[INFO]${NC}  $*"; }
warn()  { echo -e "${YELLOW}[WARN]${NC}  $*"; }
error() { echo -e "${RED}[ERROR]${NC} $*" >&2; }

if [[ ! -d "$DEPLOY" ]]; then
    error "未找到 $DEPLOY"
    exit 1
fi

if [[ "$(id -u)" -ne 0 ]]; then
    warn "非 root：无法写入 $BIN_DIR，请使用 root 执行或: sudo bash $DEPLOY/install-nx-cli.sh"
    exit 0
fi

chmod +x \
    "$DEPLOY/nx" \
    "$DEPLOY/update.sh" \
    "$DEPLOY/nexus-1panel.sh" \
    "$DEPLOY/install-nexus-fresh.sh" \
    "$DEPLOY/quick-install.sh" \
    "$DEPLOY/install-1panel-docker.sh" \
    "$DEPLOY/upgrade-1panel-docker.sh" \
    "$DEPLOY/sync-install-wizard-to-container.sh" \
    "$DEPLOY/uninstall-mysql-compose.sh" \
    "$DEPLOY/uninstall-redis-compose.sh" \
    "$DEPLOY/install-nx-cli.sh" \
    2>/dev/null || true

mkdir -p "$BIN_DIR"

link_cli() {
    local src="$1" name="$2"
    if [[ ! -f "$src" ]]; then
        warn "跳过 $name（缺少 $src）"
        return 0
    fi
    ln -sf "$src" "${BIN_DIR}/${name}"
}

link_cli "$DEPLOY/nx" nx
link_cli "$DEPLOY/update.sh" nexus-update
link_cli "$DEPLOY/install-nexus-fresh.sh" nexus-fresh
link_cli "$DEPLOY/quick-install.sh" nexus-install
link_cli "$DEPLOY/nexus-1panel.sh" nexus-1panel
link_cli "$DEPLOY/install-1panel-docker.sh" nexus-1panel-docker

if command -v nx >/dev/null 2>&1; then
    info "全局命令已就绪: nx → $(readlink -f "$(command -v nx)" 2>/dev/null || command -v nx)"
else
    error "nx 未出现在 PATH 中，请确认 $BIN_DIR 在 PATH 内"
    exit 1
fi
