#!/bin/bash
# ============================================
# Nacos 配置初始化脚本
# 1. 等待 Nacos 就绪
# 2. 替换占位符 → 导入配置到 Nacos
#
# 用法:
#   bash init-nacos.sh          首次导入（配置已存在则跳过）
#   bash init-nacos.sh --force  强制覆盖已有配置
# ============================================
set -e

FORCE="${1:-}"
if [ "$FORCE" = "--force" ] || [ "$FORCE" = "-f" ]; then
    FORCE=true
else
    FORCE=false
fi

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

NACOS_URL="${NACOS_URL:-http://localhost:8848}"
NACOS_USER="${NACOS_USER:-nacos}"
NACOS_PASS="${NACOS_PASS:-nacos}"
NAMESPACE="${NACOS_NAMESPACE:-springboot3}"          # 默认与 Maven profile 保持一致
GROUP="${NACOS_GROUP:-DEFAULT_GROUP}"
CONFIG_DIR="${DIR}/nacos/config"
MAX_RETRIES=60
RETRY_INTERVAL=5

# ============================================
# 0. 加载 .env
# ============================================
if [ -f "${DIR}/.env" ]; then
    set -a
    source "${DIR}/.env"
    set +a
fi

# 默认值
MYSQL_HOST="${MYSQL_HOST:-mysql}"
MYSQL_PORT="${MYSQL_PORT:-3306}"
MYSQL_USER="${MYSQL_USER:-root}"
MYSQL_PASS="${MYSQL_PASS:-root}"
REDIS_HOST="${REDIS_HOST:-redis}"
REDIS_PORT="${REDIS_PORT:-6379}"
REDIS_PASS="${REDIS_PASS:-}"
DB_NAME="${DB_NAME:-ghb_base}"
MINIO_HOST="${MINIO_HOST:-minio}"
MINIO_PORT="${MINIO_PORT:-9000}"
MINIO_ACCESS_KEY="${MINIO_ACCESS_KEY:-minioadmin}"
MINIO_SECRET_KEY="${MINIO_SECRET_KEY:-minioadmin}"
MINIO_BUCKET_NAME="${MINIO_BUCKET_NAME:-ghb-base}"

# ============================================
# 1. 等待 Nacos 就绪
# ============================================
echo ">>> 等待 Nacos 就绪（${NACOS_URL}）..."
for i in $(seq 1 $MAX_RETRIES); do
    if curl -s "${NACOS_URL}/nacos/v1/console/health/liveness" | grep -q "OK"; then
        echo "✅ Nacos 已就绪"
        break
    fi
    if [ "$i" -eq "$MAX_RETRIES" ]; then
        echo "❌ Nacos 启动超时"
        exit 1
    fi
    echo "   等待中...（${i}/${MAX_RETRIES}）"
    sleep $RETRY_INTERVAL
done

# ============================================
# 2. 登录（如启用认证）
# ============================================
ACCESS_TOKEN=""
AUTH_CHECK=$(curl -s -o /dev/null -w "%{http_code}" "${NACOS_URL}/nacos/v1/auth/login" -X POST 2>/dev/null || echo "404")
if [ "$AUTH_CHECK" = "200" ]; then
    echo ">>> Nacos 认证已启用，正在登录..."
    TOKEN_RESP=$(curl -s -X POST "${NACOS_URL}/nacos/v1/auth/login" \
        -d "username=${NACOS_USER}&password=${NACOS_PASS}")
    ACCESS_TOKEN=$(echo "$TOKEN_RESP" | grep -o '"accessToken":"[^"]*"' | cut -d'"' -f4 || echo "")
    if [ -n "$ACCESS_TOKEN" ]; then
        echo "✅ 登录成功"
    else
        echo "⚠️  登录失败，尝试无认证模式"
    fi
fi

# ============================================
# 3. 检查配置是否已初始化
# ============================================
CHECK_DATA_ID="jeecg.yaml"
CHECK_RESP=$(curl -s "${NACOS_URL}/nacos/v1/cs/configs?dataId=${CHECK_DATA_ID}&group=${GROUP}&tenant=${NAMESPACE}")
if [ "$FORCE" = false ] && [ -n "$CHECK_RESP" ] && [ "$CHECK_RESP" != "config data not exist" ]; then
    echo ">>> Nacos 配置已存在，跳过初始化"
    echo "   如需强制覆盖，请执行: bash deploy.sh init-nacos --force"
    exit 0
fi

if [ "$FORCE" = true ]; then
    echo ">>> --force：将覆盖已有配置"
fi

# ============================================
# 4. 创建命名空间（如指定且非 public）
# ============================================
if [ -n "$NAMESPACE" ] && [ "$NAMESPACE" != "public" ]; then
    echo ">>> 创建命名空间: ${NAMESPACE}"
    TOKEN_PARAM=""
    [ -n "$ACCESS_TOKEN" ] && TOKEN_PARAM="&accessToken=${ACCESS_TOKEN}"
    curl -s -X POST "${NACOS_URL}/nacos/v1/namespace" \
        -d "customNamespaceId=${NAMESPACE}&namespaceName=${NAMESPACE}${TOKEN_PARAM}" > /dev/null || true
fi

# ============================================
# 5. 导入配置
# ============================================
echo ">>> 开始导入 Nacos 配置..."

publish_config() {
    local data_id="$1"
    local type="$2"
    local file="$3"

    if [ ! -f "$file" ]; then
        echo "   ⚠️  跳过（文件不存在）: $file"
        return
    fi

    # 替换占位符 → 写入临时文件（避免 shell 特殊字符问题）
    local tmpfile
    tmpfile=$(mktemp)
    sed \
        -e "s|\${MYSQL_HOST}|${MYSQL_HOST}|g" \
        -e "s|\${MYSQL_PORT}|${MYSQL_PORT}|g" \
        -e "s|\${MYSQL_USER}|${MYSQL_USER}|g" \
        -e "s|\${MYSQL_PASS}|${MYSQL_PASS}|g" \
        -e "s|\${REDIS_HOST}|${REDIS_HOST}|g" \
        -e "s|\${REDIS_PORT}|${REDIS_PORT}|g" \
        -e "s|\${REDIS_PASS}|${REDIS_PASS}|g" \
        -e "s|\${DB_NAME}|${DB_NAME}|g" \
        -e "s|\${MINIO_HOST}|${MINIO_HOST}|g" \
        -e "s|\${MINIO_PORT}|${MINIO_PORT}|g" \
        -e "s|\${MINIO_ACCESS_KEY}|${MINIO_ACCESS_KEY}|g" \
        -e "s|\${MINIO_SECRET_KEY}|${MINIO_SECRET_KEY}|g" \
        -e "s|\${MINIO_BUCKET_NAME}|${MINIO_BUCKET_NAME}|g" \
        "$file" > "$tmpfile"

    local token_param=""
    [ -n "$ACCESS_TOKEN" ] && token_param="&accessToken=${ACCESS_TOKEN}"

    local http_code
    http_code=$(curl -s -o /dev/null -w "%{http_code}" -X POST "${NACOS_URL}/nacos/v1/cs/configs" \
        -d "tenant=${NAMESPACE}&dataId=${data_id}&group=${GROUP}&type=${type}${token_param}" \
        --data-urlencode "content@${tmpfile}")

    rm -f "$tmpfile"

    if [ "$http_code" = "200" ]; then
        echo "   ✅ ${data_id}"
    else
        echo "   ❌ ${data_id}（HTTP ${http_code}）"
    fi
}

# yaml 配置
publish_config "jeecg.yaml"               "yaml" "${CONFIG_DIR}/jeecg.yaml"
publish_config "jeecg-dev.yaml"           "yaml" "${CONFIG_DIR}/jeecg-dev.yaml"
publish_config "jeecg-gateway-dev.yaml"   "yaml" "${CONFIG_DIR}/jeecg-gateway-dev.yaml"

# json 配置（路由表）
publish_config "test-gateway-router"     "json" "${CONFIG_DIR}/test-gateway-router.json"

echo ""
echo "✅ Nacos 配置初始化完成"
echo "   Nacos 地址: ${NACOS_URL}/nacos"
