#!/usr/bin/env bash
# =============================================================================
# Nexus 6.0 — 公共仓库一键安装入口（参考 1Panel quick_start.sh）
#
# root 登录后一条命令:
#   curl -fsSL "http://66.154.115.8:3000/admin/Nexus/raw/branch/main/deploy/quick-install.sh" | bash
#
# 或保存后执行:
#   curl -fsSL "http://66.154.115.8:3000/admin/Nexus/raw/branch/main/deploy/quick-install.sh" -o /tmp/quick-install.sh
#   bash /tmp/quick-install.sh
#
# 可选参数会传给 install-nexus-fresh.sh，例如:
#   bash /tmp/quick-install.sh --profile 4c16g
# =============================================================================

set -euo pipefail

NEXUS_GITEA_HOST="${NEXUS_GITEA_HOST:-66.154.115.8:3000}"
NEXUS_GITEA_REPO="${NEXUS_GITEA_REPO:-admin/Nexus.git}"
NEXUS_GIT_BRANCH="${NEXUS_GIT_BRANCH:-main}"
NEXUS_ROOT="${NEXUS_ROOT:-/opt/nexus}"
NEXUS_RAW_BASE="${NEXUS_RAW_BASE:-http://${NEXUS_GITEA_HOST}/admin/Nexus/raw/branch/${NEXUS_GIT_BRANCH}}"

RED='\033[0;31m'
GREEN='\033[0;32m'
CYAN='\033[0;36m'
BLUE='\033[0;34m'
NC='\033[0m'

info()  { echo -e "${GREEN}[INFO]${NC}  $*"; }
error() { echo -e "${RED}[ERROR]${NC} $*" >&2; }
step()  { echo -e "${CYAN}[STEP]${NC}  $*"; }

usage() {
    cat <<EOF
Nexus 公共仓库一键安装

  curl -fsSL "${NEXUS_RAW_BASE}/deploy/quick-install.sh" | bash

可选参数: --profile 4c16g  --domain 你的域名  --skip-1panel-check
EOF
}

validate_script_file() {
    local f="$1"
    if [[ ! -f "$f" ]] || ! head -1 "$f" | grep -q '^#!/'; then
        return 1
    fi
    if grep -qiE '^(Not found|404)' "$f" 2>/dev/null; then
        return 1
    fi
    return 0
}

download_script() {
    local name="$1" dest="$2"
    local url base
    for base in \
        "${NEXUS_RAW_BASE}" \
        "http://${NEXUS_GITEA_HOST}/admin/Nexus/raw/${NEXUS_GIT_BRANCH}"; do
        url="${base}/deploy/${name}"
        if curl -fsSL "$url" -o "$dest" 2>/dev/null && validate_script_file "$dest"; then
            info "已下载 ${name}"
            return 0
        fi
    done
    return 1
}

run_via_git() {
    local url="http://${NEXUS_GITEA_HOST}/${NEXUS_GITEA_REPO}"
    if [[ -n "${NEXUS_GITEA_TOKEN:-}" ]]; then
        url="http://admin:${NEXUS_GITEA_TOKEN}@${NEXUS_GITEA_HOST}/${NEXUS_GITEA_REPO}"
    fi
    step "改用 git clone..."
    mkdir -p "$(dirname "$NEXUS_ROOT")"
    if [[ -d "${NEXUS_ROOT}/.git" ]]; then
        git -C "$NEXUS_ROOT" remote set-url origin "$url" 2>/dev/null || true
        git -C "$NEXUS_ROOT" fetch origin "$NEXUS_GIT_BRANCH" --depth 1 2>/dev/null || \
            git -C "$NEXUS_ROOT" fetch origin "$NEXUS_GIT_BRANCH" --prune
        git -C "$NEXUS_ROOT" reset --hard "origin/${NEXUS_GIT_BRANCH}" 2>/dev/null || \
            git -C "$NEXUS_ROOT" pull
    else
        rm -rf "$NEXUS_ROOT"
        git clone --depth 1 -b "$NEXUS_GIT_BRANCH" "$url" "$NEXUS_ROOT"
    fi
    chmod +x "${NEXUS_ROOT}/deploy/"*.sh 2>/dev/null || true
    exec bash "${NEXUS_ROOT}/deploy/install-nexus-fresh.sh" --skip-clone "$@"
}

main() {
    if [[ "$(id -u)" -ne 0 ]]; then
        error "请使用 root 执行（su - 后直接运行，不要用 sudo 包一层）"
        exit 1
    fi

    for cf in /root/.nexus-deploy.env /root/.nexus-secrets/nexus.env; do
        [[ -f "$cf" ]] && set -a && source "$cf" && set +a
    done
    unset NEXUS_SECRET_KEY NEXUS_API_KEY NEXUS_ENCRYPTION_KEY

    echo ""
    echo -e "${BLUE}╔══════════════════════════════════════════════════════════════╗${NC}"
    echo -e "${BLUE}║${NC}  Nexus 6.0 — 公共仓库一键安装                                  ${BLUE}║${NC}"
    echo -e "${BLUE}╚══════════════════════════════════════════════════════════════╝${NC}"
    echo ""

    case "${1:-}" in
        -h|--help) usage; exit 0 ;;
    esac

    local tmp
    tmp="$(mktemp /tmp/install-nexus-fresh.XXXXXX.sh)"
    if download_script "install-nexus-fresh.sh" "$tmp"; then
        chmod +x "$tmp"
        exec bash "$tmp" "$@"
    fi

    step "raw 下载失败，尝试 git clone..."
    run_via_git "$@"
}

# curl | bash 时 stdin 脚本无 BASH_SOURCE[0]，不可配合 set -u 做入口判断
main "$@"
