#!/usr/bin/env bash
# Nexus 6.0 — Upgrade Script（自动识别 Docker / Supervisor）
#
#   sudo bash deploy/upgrade.sh
#   sudo bash deploy/upgrade.sh --deploy-dir /opt/nexus
#
# Docker 1Panel：委托 deploy/nexus-1panel.sh upgrade（拉代码 + 备份 + 重建镜像）
# Supervisor 裸机：git pull + venv pip + supervisorctl restart
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
# shellcheck source=./detect_deploy_runtime.sh
source "${SCRIPT_DIR}/detect_deploy_runtime.sh"

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} $*"; }

DEPLOY_DIR=""
EXTRA_ARGS=()

while [[ $# -gt 0 ]]; do
    case "$1" in
        --deploy-dir) DEPLOY_DIR="$2"; shift 2 ;;
        --no-backup|--require-backup|--no-cache|--prune|--check|--dry-run)
            EXTRA_ARGS+=("$1"); shift ;;
        -h|--help)
            cat <<'EOF'
用法: sudo bash deploy/upgrade.sh [--deploy-dir PATH] [nexus-1panel 升级选项]

Docker 环境自动走 nexus-1panel.sh upgrade；Supervisor 环境走 venv + supervisorctl。
EOF
            exit 0
            ;;
        *) EXTRA_ARGS+=("$1"); shift ;;
    esac
done

if [[ -z "$DEPLOY_DIR" ]]; then
    DEPLOY_DIR="$(resolve_nexus_root 2>/dev/null || true)"
fi

if [[ -z "$DEPLOY_DIR" || ! -d "$DEPLOY_DIR/server" ]]; then
    error "找不到 Nexus 安装目录，请使用 --deploy-dir 指定"
    exit 1
fi

RUNTIME="$(detect_nexus_runtime "$DEPLOY_DIR")"

if [[ "$RUNTIME" == "docker" ]]; then
    info "检测到 Docker Compose 运行时，委托 nexus-1panel.sh upgrade"
    exec env NEXUS_ROOT="$DEPLOY_DIR" bash "$DEPLOY_DIR/deploy/nexus-1panel.sh" upgrade "${EXTRA_ARGS[@]}"
fi

VENV_DIR="$DEPLOY_DIR/venv"
ENV_FILE="$DEPLOY_DIR/.env"

echo ""
echo "=========================================="
echo "  Nexus 6.0 Upgrade (Supervisor)"
echo "=========================================="
echo "  Deploy: $DEPLOY_DIR"
echo ""

info "Step 1/4: Updating source code..."
if [[ -d "$DEPLOY_DIR/.git" ]]; then
    cd "$DEPLOY_DIR"
    OLD_REV="$(git rev-parse HEAD 2>/dev/null || echo unknown)"
    git pull --ff-only 2>/dev/null || {
        error "git pull failed. Resolve conflicts: cd $DEPLOY_DIR && git status"
        exit 1
    }
    NEW_REV="$(git rev-parse HEAD 2>/dev/null || echo unknown)"
    if [[ "$OLD_REV" == "$NEW_REV" ]]; then
        info "  Already up to date (no new commits)"
    else
        info "  Updated: ${OLD_REV:0:8}..${NEW_REV:0:8}"
    fi
else
    warn "  Not a git repo. Skip git pull"
fi

info "Step 2/4: Updating Python dependencies..."
if [[ -d "$VENV_DIR/bin" ]]; then
    "$VENV_DIR/bin/pip" install -q --upgrade pip
    "$VENV_DIR/bin/pip" install -q -r "$DEPLOY_DIR/requirements.txt" 2>/dev/null || {
        warn "  pip install had warnings, continuing..."
    }
else
    error "  venv not found at $VENV_DIR. Run install.sh first."
    exit 1
fi

info "Step 3/4: Restarting Nexus..."
supervisorctl restart nexus >/dev/null 2>&1 || {
    warn "  supervisorctl restart failed. Try: supervisorctl restart nexus"
}

info "Step 4/4: Verifying health..."
PORT="$(nexus_publish_port_for "$DEPLOY_DIR")"
HEALTH_OK=false
for _ in $(seq 1 15); do
    if curl -sf "http://127.0.0.1:${PORT}/health" >/dev/null 2>&1; then
        HEALTH_OK=true
        break
    fi
    sleep 2
done

echo ""
if [[ "$HEALTH_OK" == true ]]; then
    echo -e "  ${GREEN}Upgrade complete! Nexus is healthy.${NC}"
    suggest_ops_cron "$DEPLOY_DIR"
else
    echo -e "  ${YELLOW}Health check pending. Verify manually:${NC}"
    echo "    curl http://127.0.0.1:${PORT}/health"
    echo "    supervisorctl status nexus"
fi
echo ""
