#!/usr/bin/env bash
# =============================================================================
# Nexus 6.0 — 重装服务器一键入口（1Panel + Docker + Nexus）
#
# 适用：全新 VPS / 重装系统后，root 一条命令装完整栈。
#
#   curl -fsSL "http://66.154.115.8:3000/admin/Nexus/raw/branch/main/deploy/install-1panel-docker.sh" | bash
#
# 4 核 16G + 自定义域名:
#   curl -fsSL ".../install-1panel-docker.sh" | bash -s -- --profile 4c16g --domain api.example.com
#
# 已装 1Panel，只装 Nexus Docker:
#   curl -fsSL ".../install-1panel-docker.sh" | bash -s -- --skip-1panel
#
# 流程:
#   ① 可选：官方 1Panel 安装（含 Docker，交互式）
#   ② 检测 / 安装 Docker Compose
#   ③ install-nexus-fresh.sh → MySQL + Nexus 容器（Redis 自行安装）
#
# 反代：必须在 1Panel 面板 UI 配置，禁止脚本直接改 /opt/1panel/apps/
# 示例: deploy/1panel/openresty-nexus.conf.example
# =============================================================================

set -euo pipefail

NEXUS_GITEA_HOST="${NEXUS_GITEA_HOST:-66.154.115.8:3000}"
NEXUS_GIT_BRANCH="${NEXUS_GIT_BRANCH:-main}"
NEXUS_RAW_BASE="${NEXUS_RAW_BASE:-http://${NEXUS_GITEA_HOST}/admin/Nexus/raw/branch/${NEXUS_GIT_BRANCH}}"
NEXUS_ROOT="${NEXUS_ROOT:-/opt/nexus}"
NEXUS_DOMAIN="${NEXUS_DOMAIN:-api.synaglobal.vip}"
NEXUS_PROFILE="${NEXUS_PROFILE:-2c8g}"

PANEL_INSTALL_URL="${PANEL_INSTALL_URL:-https://resource.1panel.pro/v2/quick_start.sh}"

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

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

WITH_1PANEL=auto
SKIP_1PANEL=false
SKIP_DOCKER_INSTALL=false
EXTRA_ARGS=()

usage() {
    cat <<EOF
重装服务器 — 1Panel + Docker + Nexus 一键安装

  curl -fsSL "${NEXUS_RAW_BASE}/deploy/install-1panel-docker.sh" | bash

选项（传给 bash -s --）:
  --with-1panel       未装 1Panel 时先跑官方安装脚本（交互式）
  --skip-1panel       跳过 1Panel，只装 Nexus Docker 栈
  --skip-docker-install  不自动装 Docker（已在 1Panel 装好）
  --profile 2c8g|4c16g|1c4g
  --domain NAME
  --root PATH
  -h, --help

说明:
  - 1Panel 官方安装为交互式（端口/用户/密码），装完记下面板地址
  - Nexus 密钥按本机自动生成，备份在 /root/.nexus-install-secrets-*.env
  - 网站反代请在 1Panel UI 操作，勿手工改 /opt/1panel/apps/
EOF
}

while [[ $# -gt 0 ]]; do
    case "$1" in
        -h|--help) usage; exit 0 ;;
        --with-1panel) WITH_1PANEL=true; shift ;;
        --skip-1panel) SKIP_1PANEL=true; WITH_1PANEL=false; shift ;;
        --skip-docker-install) SKIP_DOCKER_INSTALL=true; shift ;;
        --profile|--domain|--root)
            EXTRA_ARGS+=("$1" "$2")
            shift 2
            ;;
        --skip-clone|--skip-1panel-check)
            EXTRA_ARGS+=("$1")
            shift
            ;;
        *) EXTRA_ARGS+=("$1"); shift ;;
    esac
done

banner() {
    echo ""
    echo -e "${BLUE}╔══════════════════════════════════════════════════════════════╗${NC}"
    echo -e "${BLUE}║${NC}  Nexus — 1Panel + Docker + Nexus 一键安装                     ${BLUE}║${NC}"
    echo -e "${BLUE}║${NC}  域名: ${NEXUS_DOMAIN}   档位: ${NEXUS_PROFILE}                      ${BLUE}║${NC}"
    echo -e "${BLUE}╚══════════════════════════════════════════════════════════════╝${NC}"
    echo ""
}

require_root() {
    if [[ "$(id -u)" -ne 0 ]]; then
        error "请使用 root 执行（su - 后直接运行）"
        exit 1
    fi
}

load_deploy_env() {
    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
}

has_1panel() {
    command -v 1pctl >/dev/null 2>&1
}

has_docker_compose() {
    docker compose version >/dev/null 2>&1
}

phase_1panel() {
    if [[ "$SKIP_1PANEL" == true ]]; then
        info "跳过 1Panel 安装（--skip-1panel）"
        return 0
    fi

    if has_1panel; then
        info "已安装 1Panel"
        if 1pctl user-info >/dev/null 2>&1; then
            1pctl user-info 2>/dev/null | grep -E '面板地址|面板用户' || true
        else
            warn "1pctl user-info 失败，面板可能需修复；继续安装 Nexus…"
        fi
        return 0
    fi

    if [[ "$WITH_1PANEL" == auto ]]; then
        echo ""
        warn "未检测到 1Panel（1pctl 不存在）"
        echo "  ① 先装 1Panel（推荐，含 Docker）再装 Nexus"
        echo "  ② 跳过 1Panel，仅装 Nexus Docker（需本机已有 Docker）"
        echo ""
        read -r -p "是否现在安装 1Panel? [Y/n]: " ans
        case "${ans:-Y}" in
            n|N) WITH_1PANEL=false ;;
            *) WITH_1PANEL=true ;;
        esac
    fi

    if [[ "$WITH_1PANEL" != true ]]; then
        warn "未安装 1Panel，将仅安装 Nexus Docker 栈"
        return 0
    fi

    step "安装 1Panel（官方脚本，交互式）..."
    info "下载: $PANEL_INSTALL_URL"
    local tmp
    tmp="$(mktemp /tmp/1panel-quick-start.XXXXXX.sh)"
    if ! curl -fsSL "$PANEL_INSTALL_URL" -o "$tmp"; then
        error "下载 1Panel 安装脚本失败"
        exit 1
    fi
    chmod +x "$tmp"
    echo ""
    warn "接下来为 1Panel 官方安装向导，请按提示设置端口、安全入口、用户名、密码"
    warn "安装目录建议默认 /opt"
    echo ""
    bash "$tmp"
    rm -f "$tmp"

    if ! has_1panel; then
        error "1Panel 安装后仍未找到 1pctl，请检查安装日志"
        exit 1
    fi
    info "1Panel 安装完成"
    1pctl user-info 2>/dev/null || true
    echo ""
    warn "请在 1Panel → 应用商店 安装 OpenResty（用于 HTTPS 反代）"
    read -r -p "OpenResty 已装好或稍后自行安装，按 Enter 继续 Nexus 安装..."
}

install_docker_engine() {
    step "安装 Docker Engine + Compose 插件..."
    if command -v apt-get >/dev/null 2>&1; then
        export DEBIAN_FRONTEND=noninteractive
        apt-get update -qq
        apt-get install -y -qq ca-certificates curl >/dev/null
        curl -fsSL https://get.docker.com | sh
        systemctl enable --now docker 2>/dev/null || true
    elif command -v dnf >/dev/null 2>&1; then
        dnf install -y -q docker docker-compose-plugin >/dev/null 2>&1 || \
            curl -fsSL https://get.docker.com | sh
        systemctl enable --now docker 2>/dev/null || true
    else
        curl -fsSL https://get.docker.com | sh
    fi
}

phase_docker() {
    step "检测 Docker Compose..."
    if has_docker_compose; then
        info "Docker Compose: $(docker compose version --short 2>/dev/null || docker compose version | head -1)"
        return 0
    fi

    if [[ "$SKIP_DOCKER_INSTALL" == true ]]; then
        error "未检测到 docker compose，且已指定 --skip-docker-install"
        error "请在 1Panel → 容器 安装 Docker，或去掉该参数"
        exit 1
    fi

    warn "未检测到 docker compose"
    if has_1panel; then
        warn "建议在 1Panel → 容器 安装 Docker 后重新运行本脚本"
        read -r -p "是否尝试用 get.docker.com 自动安装? [y/N]: " ans
        [[ "${ans:-N}" == y || "${ans:-N}" == Y ]] || exit 1
    else
        info "自动安装 Docker（get.docker.com）..."
    fi

    install_docker_engine

    if ! has_docker_compose; then
        error "Docker 安装后仍无 compose 插件，请手动安装 docker-compose-plugin"
        exit 1
    fi
    info "Docker Compose 就绪"
}

download_fresh_installer() {
    local name="install-nexus-fresh.sh" dest
    dest="$(mktemp /tmp/install-nexus-fresh.XXXXXX.sh)"
    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 && head -1 "$dest" | grep -q '^#!/'; then
            chmod +x "$dest"
            echo "$dest"
            return 0
        fi
    done
    return 1
}

phase_nexus() {
    step "安装 Nexus Docker 栈（MySQL + Nexus；Redis 请自行安装）..."
    local installer
    if [[ -x "${NEXUS_ROOT}/deploy/install-nexus-fresh.sh" ]]; then
        installer="${NEXUS_ROOT}/deploy/install-nexus-fresh.sh"
        info "使用本地: $installer"
        exec bash "$installer" --skip-1panel-check "${EXTRA_ARGS[@]}"
    fi

    if installer="$(download_fresh_installer)"; then
        info "已下载 install-nexus-fresh.sh"
        exec bash "$installer" --skip-1panel-check "${EXTRA_ARGS[@]}"
    fi

    error "无法获取 install-nexus-fresh.sh，请检查 Gitea 可达性"
    exit 1
}

main() {
    banner
    require_root
    load_deploy_env
    phase_1panel
    phase_docker
    phase_nexus
}

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