#!/usr/bin/env bash
set -euo pipefail

echo "======================================="
echo "ARGUS DNS监控功能测试"
echo "======================================="
echo ""

# 记录测试开始时间
test_start_time=$(date +%s)

# 函数：显示测试步骤
show_step() {
    echo ""
    echo "🔄 Step $1: $2"
    echo "----------------------------------------"
}

# 函数：验证步骤结果
verify_step() {
    if [ $? -eq 0 ]; then
        echo "✅ $1 - SUCCESS"
    else
        echo "❌ $1 - FAILED"
        exit 1
    fi
}

# 函数：等待服务就绪
wait_for_services() {
    echo "[INFO] Waiting for services to be ready..."
    local max_attempts=60
    local attempt=1

    while [ $attempt -le $max_attempts ]; do
        if curl -fs http://localhost:9200/_cluster/health >/dev/null 2>&1 && \
           curl -fs http://localhost:5601/api/status >/dev/null 2>&1; then
            echo "[OK] Services are ready!"
            return 0
        fi
        echo "    Waiting for services... ($attempt/$max_attempts)"
        sleep 5
        ((attempt++))
    done

    echo "[ERROR] Services not ready after $max_attempts attempts"
    return 1
}

# 函数：检查容器中的/etc/resolv.conf
check_resolv_conf() {
    local service_name=$1
    local expected_dns=$2

    echo "[INFO] 检查 $service_name 容器的 /etc/resolv.conf..."

    local resolv_content=$(docker exec "${service_name}" cat /etc/resolv.conf 2>/dev/null || echo "")
    if echo "$resolv_content" | grep -q "nameserver $expected_dns"; then
        echo "✅ $service_name resolv.conf contains nameserver $expected_dns"
        return 0
    else
        echo "❌ $service_name resolv.conf does not contain nameserver $expected_dns"
        echo "实际内容:"
        echo "$resolv_content"
        return 1
    fi
}

# 函数：检查DNS监控日志
check_dns_monitor_logs() {
    local service_name=$1

    echo "[INFO] 检查 $service_name 的DNS监控日志..."

    local dns_logs=$(docker exec "$service_name" tail -n 20 /var/log/supervisor/dns-monitor.log 2>/dev/null || echo "")
    if [ -n "$dns_logs" ]; then
        echo "✅ $service_name DNS监控日志存在"
        echo "最近的日志:"
        echo "$dns_logs"
        return 0
    else
        echo "❌ $service_name DNS监控日志为空或不存在"
        return 1
    fi
}

# 函数：确保目录结构存在
ensure_directories() {
    echo "[INFO] 确保目录结构存在..."
    # 确保目录存在
    mkdir -p ./private/argus/etc/
    echo "✅ 目录结构准备完成（注：使用真实的update-dns.sh脚本）"
}

# 开始DNS监控测试
show_step "1" "Bootstrap - Initialize environment"
./scripts/01_bootstrap.sh
verify_step "Bootstrap"

# 确保目录结构
ensure_directories

show_step "2" "Startup - Start all services"
./scripts/02_up.sh
verify_step "Service startup"

# 等待服务完全就绪
wait_for_services || exit 1

show_step "3" "Create initial DNS configuration"
# 创建初始的DNS配置文件 - 只有一个IP
echo "[INFO] 创建初始的dns.conf文件 (8.8.8.8)..."
cat > ./private/argus/etc/dns.conf << 'EOF'
8.8.8.8
EOF

echo "✅ 初始dns.conf文件创建成功 (8.8.8.8)"
verify_step "Initial DNS configuration creation"

# 等待DNS监控检测到配置文件
echo "[INFO] 等待DNS监控检测并处理初始配置..."
sleep 15

show_step "4" "Verify initial DNS configuration processing"
# 检查两个容器的DNS监控日志
check_dns_monitor_logs "logging-mvp-es-1"
verify_step "Elasticsearch DNS monitor logs"

check_dns_monitor_logs "logging-mvp-kibana-1"
verify_step "Kibana DNS monitor logs"

# 检查resolv.conf是否包含新的DNS服务器
check_resolv_conf "logging-mvp-es-1" "8.8.8.8"
verify_step "Elasticsearch resolv.conf initial check"

check_resolv_conf "logging-mvp-kibana-1" "8.8.8.8"
verify_step "Kibana resolv.conf initial check"

show_step "5" "Modify DNS configuration and test auto-update"
# 修改DNS配置文件 - 改为另一个IP
echo "[INFO] 修改dns.conf文件，改为1.1.1.1..."
cat > ./private/argus/etc/dns.conf << 'EOF'
1.1.1.1
EOF

echo "✅ dns.conf文件更新成功，改为1.1.1.1"

# 等待DNS监控检测到配置变化
echo "[INFO] 等待DNS监控检测配置变化并执行更新..."
sleep 15

show_step "6" "Verify DNS configuration auto-update"
# 再次检查DNS监控日志，应该看到配置变化检测
echo "[INFO] 检查DNS监控是否检测到配置变化..."

# 检查elasticsearch容器
echo "[INFO] 检查elasticsearch容器的DNS监控日志（最近30行）..."
docker exec logging-mvp-es-1 tail -n 30 /var/log/supervisor/dns-monitor.log || true

# 检查kibana容器
echo "[INFO] 检查kibana容器的DNS监控日志（最近30行）..."
docker exec logging-mvp-kibana-1 tail -n 30 /var/log/supervisor/dns-monitor.log || true

# 验证新的DNS服务器是否被添加到resolv.conf
check_resolv_conf "logging-mvp-es-1" "1.1.1.1"
verify_step "Elasticsearch resolv.conf after update"

check_resolv_conf "logging-mvp-kibana-1" "1.1.1.1"
verify_step "Kibana resolv.conf after update"

show_step "7" "Final verification - Check DNS configuration"
# 最终验证DNS配置
echo "[INFO] 最终验证elasticsearch容器的resolv.conf..."
docker exec logging-mvp-es-1 cat /etc/resolv.conf

echo "[INFO] 最终验证kibana容器的resolv.conf..."
docker exec logging-mvp-kibana-1 cat /etc/resolv.conf

echo "[INFO] 最终dns.conf内容:"
cat ./private/argus/etc/dns.conf

verify_step "Final DNS configuration verification"

show_step "8" "Cleanup - Stop all services"
./scripts/05_down.sh
verify_step "Service cleanup"

# 清理测试文件
rm -f ./private/argus/etc/dns.conf
# 注：不删除update-dns.sh，因为这是真实的脚本

# 计算总测试时间
test_end_time=$(date +%s)
total_time=$((test_end_time - test_start_time))

echo ""
echo "======================================="
echo "🎉 DNS监控功能测试完成!"
echo "======================================="
echo "📊 测试总结:"
echo "   • 总耗时: ${total_time}秒"
echo "   • 初始DNS配置: 8.8.8.8"
echo "   • 更新DNS配置: 1.1.1.1"
echo "   • DNS监控脚本正常工作"
echo "   • 容器resolv.conf自动覆盖更新成功"
echo ""
echo "✅ DNS自动更新功能测试通过!"
echo ""