#!/usr/bin/env bash
# =============================================================================
# 卸载 Nexus 旧版 Compose 内置 Redis 容器
#
# 适用：已从 docker-compose.prod.yml 移除 redis 服务，改用宿主机/1Panel 自建 Redis。
# 不会卸载 apt/1Panel 安装的 Redis，仅删除 Docker 容器与（可选）数据卷。
#
#   bash deploy/uninstall-redis-compose.sh
#   bash deploy/uninstall-redis-compose.sh --purge-volume   # 同时删 redis-data 卷
# =============================================================================

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 遗留 Redis 容器

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

选项:
  --purge-volume   删除 nexus-prod_redis-data 数据卷（不可恢复）
  -h, --help       显示帮助

说明:
  - 不卸载宿主机 redis-server / 1Panel 应用商店 Redis
  - 卸载后请在宿主机安装 Redis，安装向导步骤 2 须能 ping 通
EOF
}

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

if [[ "$(id -u)" -ne 0 ]]; then
    error "请使用 root 执行"
    exit 1
fi

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 "$name" >/dev/null 2>&1 || true
        removed=$((removed + 1))
    fi
}

# 常见 Compose 命名
for pattern in nexus-prod-redis-1 nexus-prod-redis nexus-redis-1; do
    stop_rm_container "$pattern"
done

# 名称含 nexus 且含 redis 的容器
while IFS= read -r c; do
    [[ -z "$c" ]] && continue
    stop_rm_container "$c"
done < <(docker ps -a --format '{{.Names}}' | grep -iE 'nexus.*redis|redis.*nexus' || true)

# 若旧 compose 仍定义 redis 服务
if [[ -f "${NEXUS_ROOT}/${COMPOSE_FILE}" ]]; then
    if grep -q '^  redis:' "${NEXUS_ROOT}/${COMPOSE_FILE}" 2>/dev/null; then
        warn "compose 仍含 redis 服务，尝试 compose rm..."
        local_env=()
        [[ -f "${NEXUS_ROOT}/docker/.env.prod" ]] && local_env+=(--env-file "${NEXUS_ROOT}/docker/.env.prod")
        prof="${NEXUS_ROOT}/docker/.host-profile"
        if [[ -f "$prof" ]]; then
            p="$(tr -d '\r\n' <"$prof")"
            [[ -f "${NEXUS_ROOT}/docker/profiles/${p}.env" ]] && local_env+=(--env-file "${NEXUS_ROOT}/docker/profiles/${p}.env")
        fi
        (cd "$NEXUS_ROOT" && docker compose -f "$COMPOSE_FILE" "${local_env[@]}" stop redis 2>/dev/null || true)
        (cd "$NEXUS_ROOT" && docker compose -f "$COMPOSE_FILE" "${local_env[@]}" rm -f redis 2>/dev/null || true)
        removed=$((removed + 1))
    fi
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.*redis|redis.*nexus' || true)
fi

echo ""
if [[ "$removed" -gt 0 ]]; then
    info "Compose Redis 容器已卸载。"
else
    info "未发现 Nexus Compose Redis 容器（可能已删除）。"
fi

echo ""
info "下一步：在宿主机或 1Panel 安装 Redis，确认监听 6379："
echo "  apt install -y redis-server && systemctl enable --now redis-server"
echo "  redis-cli ping   # 期望 PONG"
echo ""
info "Docker 内 Nexus 连接宿主机 Redis：安装向导 / .env 使用 host.docker.internal:6379"
