#!/usr/bin/env bash
# =============================================================================
# 卸载 Nexus 旧版 Compose 内置 MySQL 容器
#
#   bash deploy/uninstall-mysql-compose.sh
#   bash deploy/uninstall-mysql-compose.sh --purge-volume
# =============================================================================

set -euo pipefail

NEXUS_ROOT="${NEXUS_ROOT:-/opt/nexus}"
COMPOSE_FILE="${COMPOSE_FILE:-docker/docker-compose.prod.yml}"
PURGE_VOLUME=false

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; }

usage() {
    cat <<EOF
卸载 Nexus Compose 遗留 MySQL 容器

  bash deploy/uninstall-mysql-compose.sh [--purge-volume]

说明:
  - 不卸载宿主机/1Panel 自建的 MySQL
  - 卸载后请自建库 nexus + 用户，安装向导步骤 3 填写连接信息
EOF
}

compose_env_args() {
    local_env=()
    [[ -f "${NEXUS_ROOT}/docker/.env.prod" ]] && local_env+=(--env-file "${NEXUS_ROOT}/docker/.env.prod")
    local prof="${NEXUS_ROOT}/docker/.host-profile"
    if [[ -f "$prof" ]]; then
        local p
        p="$(tr -d '\r\n' <"$prof")"
        [[ -f "${NEXUS_ROOT}/docker/profiles/${p}.env" ]] && local_env+=(--env-file "${NEXUS_ROOT}/docker/profiles/${p}.env")
    fi
}

while [[ $# -gt 0 ]]; do
    case "$1" in
        -h|--help) usage; exit 0 ;;
        --purge-volume) PURGE_VOLUME=true; shift ;;
        *) error "未知参数: $1"; usage; exit 1 ;;
    esac
done

[[ "$(id -u)" -eq 0 ]] || { error "请使用 root 执行"; exit 1; }

removed=0

stop_rm_container() {
    local name="$1"
    if docker ps -a --format '{{.Names}}' | grep -qx "$name"; then
        info "停止并删除容器: $name"
        docker stop "$name" >/dev/null 2>&1 || true
        docker rm -f "$name" >/dev/null 2>&1 || true
        removed=$((removed + 1))
    fi
}

for pattern in nexus-prod-mysql-1 nexus-prod-mysql nexus-mysql-1; do
    stop_rm_container "$pattern"
done

while IFS= read -r c; do
    [[ -z "$c" ]] && continue
    stop_rm_container "$c"
done < <(docker ps -a --format '{{.Names}}' | grep -iE 'nexus.*mysql|mysql.*nexus' || true)

compose_env_args
if [[ -f "${NEXUS_ROOT}/${COMPOSE_FILE}" ]] && grep -q '^  mysql:' "${NEXUS_ROOT}/${COMPOSE_FILE}" 2>/dev/null; then
    warn "compose 仍含 mysql 服务，尝试 compose rm..."
    (cd "$NEXUS_ROOT" && docker compose -f "$COMPOSE_FILE" "${local_env[@]}" stop mysql 2>/dev/null || true)
    (cd "$NEXUS_ROOT" && docker compose -f "$COMPOSE_FILE" "${local_env[@]}" rm -f mysql 2>/dev/null || true)
    removed=$((removed + 1))
elif [[ -f "${NEXUS_ROOT}/${COMPOSE_FILE}" && -f "${NEXUS_ROOT}/docker/.env.prod" ]]; then
    info "Compose --remove-orphans（从 nexus-prod 项目移除 mysql 孤儿容器）..."
    compose_files=(-f "${NEXUS_ROOT}/${COMPOSE_FILE}")
    if docker network inspect 1panel-network >/dev/null 2>&1 \
        && [[ -f "${NEXUS_ROOT}/docker/docker-compose.1panel.yml" ]]; then
        compose_files+=(-f "${NEXUS_ROOT}/docker/docker-compose.1panel.yml")
    fi
    (cd "$NEXUS_ROOT" && docker compose "${compose_files[@]}" "${local_env[@]}" up -d --remove-orphans 2>/dev/null || true)
    while IFS= read -r c; do
        [[ -z "$c" ]] && continue
        stop_rm_container "$c"
    done < <(docker ps -a --format '{{.Names}}' | grep -iE 'nexus.*mysql|mysql.*nexus' || true)
fi

if [[ "$PURGE_VOLUME" == true ]]; then
    while IFS= read -r vol; do
        [[ -z "$vol" ]] && continue
        info "删除数据卷: $vol"
        docker volume rm "$vol" 2>/dev/null || warn "无法删除卷 $vol"
    done < <(docker volume ls -q | grep -iE 'nexus.*mysql|mysql.*nexus' || true)
fi

leftover="$(docker ps -a --format '{{.Names}}' | grep -iE 'nexus.*mysql|mysql.*nexus' || true)"
if [[ -n "$leftover" ]]; then
    warn "仍有 MySQL 相关容器:"
    echo "$leftover" | sed 's/^/  /'
    warn "若确认为 Compose 遗留，可: docker rm -f <容器名>"
elif [[ "$removed" -gt 0 ]]; then
    info "Compose MySQL 容器已卸载。"
else
    info "未发现 Nexus Compose MySQL 容器。"
fi

echo ""
info "当前 Nexus 栈:"
docker ps --format 'table {{.Names}}\t{{.Image}}\t{{.Status}}' | grep -i nexus || docker ps --format 'table {{.Names}}\t{{.Image}}\t{{.Status}}'
echo ""
info "下一步：自建 MySQL 数据库与用户，安装向导步骤 3 使用 host.docker.internal:3306"
