#!/usr/bin/env bash
# Diagnose 1Panel Redis auth from Nexus container network perspective.
# Usage:
#   REDIS_PASS='redis_WP3NyN' bash deploy/test-1panel-redis.sh
#   bash deploy/test-1panel-redis.sh   # prompts for password
set -euo pipefail

NEXUS_ROOT="${NEXUS_ROOT:-/opt/nexus}"
ENV_PROD="${NEXUS_ROOT}/docker/.env.prod"

info() { echo -e "\033[0;32m[INFO]\033[0m  $*"; }
ok() { echo -e "\033[0;32m[OK]\033[0m    $*"; }
fail() { echo -e "\033[0;31m[FAIL]\033[0m  $*"; }

pick_redis_container() {
    if [[ -n "${REDIS_CONTAINER:-}" ]]; then
        echo "$REDIS_CONTAINER"
        return 0
    fi
    local h
    h="$(grep -E '^NEXUS_1PANEL_REDIS_HOST=' "$ENV_PROD" 2>/dev/null | cut -d= -f2- || true)"
    if [[ -n "$h" ]]; then
        echo "$h"
        return 0
    fi
    if [[ -x "$NEXUS_ROOT/deploy/detect-1panel-services.sh" ]]; then
        h="$("$NEXUS_ROOT/deploy/detect-1panel-services.sh" 2>/dev/null | sed -n 's/^NEXUS_1PANEL_REDIS_HOST=//p' | head -1)"
        [[ -n "$h" ]] && echo "$h" && return 0
    fi
    docker ps --format '{{.Names}}' | grep -iE '^1Panel-redis-' | head -1 || true
}

try_ping() {
    local label="$1" url="$2"
    local nexus
    nexus="$(docker ps --format '{{.Names}}' | grep -E 'nexus-prod-nexus|nexus-nexus-1' | head -1 || true)"
    if [[ -z "$nexus" ]]; then
        fail "未找到 Nexus 容器"
        return 1
    fi
    if docker exec "$nexus" python3 -c "
import redis
r = redis.Redis.from_url('${url}', socket_timeout=3)
print(r.ping())
" 2>/dev/null | grep -q True; then
        ok "$label → $url"
        return 0
    fi
    fail "$label"
    return 1
}

main() {
    local redis_host pass
    redis_host="$(pick_redis_container)"
    [[ -n "$redis_host" ]] || { fail "未找到 Redis 容器/主机名"; exit 1; }
    info "Redis 主机: $redis_host"

    if [[ -z "${REDIS_PASS:-}" ]]; then
        read -r -s -p "1Panel Redis 密码（应用参数）: " pass
        echo ""
    else
        pass="$REDIS_PASS"
    fi

    echo ""
    info "从 Nexus 容器内尝试多种 URL 格式（807f4c2 修复后）..."
    local any=0
    try_ping "无认证" "redis://${redis_host}:6379/0" && any=1 || true
    if [[ -n "$pass" ]]; then
        try_ping "仅密码 (:pass@)" "redis://:${pass}@${redis_host}:6379/0" && any=1 || true
        try_ping "default 用户" "redis://default:${pass}@${redis_host}:6379/0" && any=1 || true
        info "跳过 root 用户探测 — 1Panel Redis 无 root 账号"
    fi

    echo ""
    if [[ "$any" -eq 1 ]]; then
        ok "至少一种格式可用"
        echo ""
        info "安装向导步骤 3：1Panel Redis 无账号，只填密码（后端自动用 :pass@ 或 default）"
        info "已有 .env 时写入 NEXUS_REDIS_URL，例如:"
        info "  redis://:${pass}@${redis_host}:6379/0"
        info "  或 redis://default:${pass}@${redis_host}:6379/0"
        exit 0
    fi
    fail "全部失败。请在 1Panel → Redis → 参数 核对密码，或检查 Nexus 是否在 1panel-network"
    info "本机: docker exec -it ${redis_host} redis-cli -u 'redis://:密码@127.0.0.1:6379' ping"
    exit 1
}

main "$@"
