#!/bin/bash
set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$SCRIPT_DIR"

# 如果 docker-compose.yml 不存在，自动下载
if [ ! -f docker-compose.yml ]; then
    echo "📥 下载 docker-compose.yml..."
    wget -q https://gitea.timxx.cn/admin/CloudSearch/raw/branch/master/source_clean/docker-compose.yml || {
        echo "❌ 下载失败，请检查网络"
        exit 1
    }
fi

echo "🔍 检测 Redis..."

EXISTING_REDIS=$(docker ps --format '{{.Names}}' | grep -i redis | head -1)

if [ -n "$EXISTING_REDIS" ]; then
    if docker network inspect cloudsearch-net --format '{{range .Containers}}{{.Name}} {{end}}' 2>/dev/null | grep -qw "$EXISTING_REDIS"; then
        echo "✅ 已有 Redis: $EXISTING_REDIS (已加入 cloudsearch-net)，跳过创建"
    else
        echo "✅ 已有 Redis: $EXISTING_REDIS，正在加入网络..."
        docker network connect cloudsearch-net "$EXISTING_REDIS" 2>/dev/null || true
        echo "   ✅ 已加入 cloudsearch-net"
    fi

    # 检测 Redis 密码 (多种来源)
    REDIS_PASS=""

    # 方法1: 从命令行参数 --requirepass
    PASS_FROM_CMD=$(docker inspect "$EXISTING_REDIS" --format '{{range .Config.Cmd}}{{println .}}{{end}}' 2>/dev/null | grep -A1 'requirepass' | tail -1 | tr -d '[:space:]' || true)
    if [ -n "$PASS_FROM_CMD" ] && [ "$PASS_FROM_CMD" != "redis-server" ] && [ "$PASS_FROM_CMD" != "/etc/redis/redis.conf" ]; then
        REDIS_PASS="$PASS_FROM_CMD"
        echo "   🔑 从启动参数检测到 Redis 密码"
    fi

    # 方法2: 从 redis.conf 读取 (1Panel 常见配置方式)
    if [ -z "$REDIS_PASS" ]; then
        PASS_FROM_CONF=$(docker exec "$EXISTING_REDIS" cat /etc/redis/redis.conf 2>/dev/null | grep '^requirepass ' | awk '{print $2}' | tr -d '"' || true)
        if [ -n "$PASS_FROM_CONF" ]; then
            REDIS_PASS="$PASS_FROM_CONF"
            echo "   🔑 从 redis.conf 检测到 Redis 密码"
        fi
    fi

    # 方法3: 尝试无密码连接测试
    if [ -z "$REDIS_PASS" ]; then
        if docker exec "$EXISTING_REDIS" redis-cli ping 2>/dev/null | grep -q PONG; then
            echo "   ℹ️  Redis 无密码（已通过连接测试验证）"
        else
            # 有密码但检测不到 — 尝试从 redis-cli 的错误消息中提取
            AUTH_ERR=$(docker exec "$EXISTING_REDIS" redis-cli ping 2>&1 || true)
            if echo "$AUTH_ERR" | grep -q "NOAUTH\|AUTH"; then
                echo "   ⚠️  Redis 需要密码但无法自动检测，请手动设置 REDIS_URL"
                echo "   提示: 在 .env 中设置 REDIS_URL=redis://:密码@${EXISTING_REDIS}:6379"
            fi
        fi
    fi

    if [ -n "$REDIS_PASS" ]; then
        # 对密码中的特殊字符进行URL编码
        ENCODED_PASS=$(python3 -c "import urllib.parse; print(urllib.parse.quote('$REDIS_PASS', safe=''))" 2>/dev/null || echo "$REDIS_PASS")
        REDIS_URL="redis://:${ENCODED_PASS}@${EXISTING_REDIS}:6379"
    else
        REDIS_URL="redis://${EXISTING_REDIS}:6379"
    fi
    PROFILE=""
else
    echo "📦 未检测到 Redis，将自动创建..."
    REDIS_URL="redis://CloudSearch_Redis:6379"
    PROFILE="--profile full"
fi

# 生成 .env
cat > .env <<EOF
REDIS_URL=${REDIS_URL}
CORS_ORIGIN=https://zy.hk.timxx.cn
JWT_SECRET=cloudsearch-jwt-secret-2024
ADMIN_PASSWORD=0nL5kLhMIJ1121PYmQb25A
LOG_LEVEL=info
EOF

echo ""
echo "🚀 启动服务..."
docker compose $PROFILE up -d

echo ""
echo "✅ 部署完成"
docker compose ps
