#!/bin/bash
# 域名配置测试脚本

echo "🔍 开始测试域名配置..."
echo "=========================================="

# 测试函数
test_domain() {
    local domain=$1
    local expected_title=$2
    local description=$3
    
    echo -n "测试 $domain ($description)... "
    
    # 使用curl测试
    result=$(curl -H "Host: $domain" -s -f http://127.0.0.1/ 2>/dev/null | grep -o "<title>[^<]*</title>" | head -1 || echo "ERROR")
    
    if [[ "$result" == *"$expected_title"* ]]; then
        echo "✅ 成功"
        echo "   标题: $result"
    else
        echo "❌ 失败"
        echo "   期望: <title>$expected_title</title>"
        echo "   实际: $result"
    fi
}

# 测试各个域名
test_domain "www.xmrap.com" "辰界科技 AI工具箱" "主网站"
test_domain "xmrap.com" "辰界科技 AI工具箱" "主域名（自动跳转到www）"
test_domain "edu.xmrap.com" "AI 教学助手" "教育网站"
test_domain "openclaw.xmrap.com" "OpenClaw 文件服务 - 文件目录" "OpenClaw文件服务"

# 测试具体页面
echo ""
echo "📄 测试具体页面..."
echo -n "测试 edu.xmrap.com/beian.html... "
beian_test=$(curl -H "Host: edu.xmrap.com" -s -f http://127.0.0.1/beian.html 2>/dev/null | grep -o "京ICP备2026000000号" || echo "ERROR")
if [[ "$beian_test" == "京ICP备2026000000号" ]]; then
    echo "✅ 成功"
else
    echo "❌ 失败"
fi

# 测试Nginx状态
echo ""
echo "🔧 测试Nginx状态..."
nginx_status=$(sudo systemctl is-active nginx)
if [[ "$nginx_status" == "active" ]]; then
    echo "✅ Nginx运行正常"
else
    echo "❌ Nginx状态: $nginx_status"
fi

# 测试端口监听
echo ""
echo "🔌 测试端口监听..."
port_80=$(sudo netstat -tln | grep ":80 " | wc -l)
if [[ $port_80 -gt 0 ]]; then
    echo "✅ 80端口监听正常"
else
    echo "❌ 80端口未监听"
fi

# 测试目录权限
echo ""
echo "📂 测试目录权限..."
check_dir() {
    local dir=$1
    local name=$2
    
    if [[ -d "$dir" ]]; then
        echo "✅ $name目录存在: $dir"
    else
        echo "❌ $name目录不存在: $dir"
    fi
}

check_dir "/home/ubuntu/output/projects/openclaw-www" "主网站"
check_dir "/home/ubuntu/output/education_website" "教育网站"

# 测试配置文件
echo ""
echo "⚙️  测试Nginx配置..."
config_test=$(sudo nginx -t 2>&1)
if [[ $? -eq 0 ]]; then
    echo "✅ Nginx配置语法正确"
else
    echo "❌ Nginx配置错误:"
    echo "$config_test"
fi

# 显示当前配置
echo ""
echo "📋 当前Nginx站点配置:"
ls -la /etc/nginx/sites-enabled/

echo ""
echo "🌐 访问地址汇总:"
echo "1. 主网站: http://www.xmrap.com"
echo "2. 教育网站: http://edu.xmrap.com"
echo "3. OpenClaw文件服务: http://openclaw.xmrap.com"
echo "4. 文档目录: http://openclaw.xmrap.com/documents/"
echo "5. 项目目录: http://openclaw.xmrap.com/projects/"

echo ""
echo "=========================================="
echo "🚀 测试完成!"