#!/bin/bash

# ==============================================
# UpSeller Domain Network Connectivity Tester (macOS)
# ==============================================

# 检查必需命令是否存在
check_commands() {
    local missing_commands=()
    for cmd in ping traceroute; do
        if ! command -v "$cmd" &> /dev/null; then
            missing_commands+=("$cmd")
        fi
    done
    
    if [ ${#missing_commands[@]} -gt 0 ]; then
        echo "❌ 缺少必需命令: ${missing_commands[*]}"
        echo "请安装缺少的命令后重试"
        exit 1
    fi
}

# IP解析函数
get_domain_ip() {
    local domain="$1"
    local ip
    
    if command -v dig &> /dev/null; then
        # 使用dig，只获取A记录的IP地址
        ip=$(dig +short "$domain" A | grep -E '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$' | head -1)
    else
        # 备选方案：使用nslookup
        ip=$(nslookup "$domain" 2>/dev/null | awk '/^Address: / { print $2 }' | head -1)
    fi
    
    echo "$ip"
}

# 安全创建日志文件
create_log_file() {
    local log_dir
    
    # 尝试不同的日志目录
    if [ -w "$HOME/Desktop" ] 2>/dev/null; then
        log_dir="$HOME/Desktop"
    elif [ -w "$HOME" ] 2>/dev/null; then
        log_dir="$HOME"
    else
        log_dir="/tmp"
    fi
    
    local timestamp=$(date +%Y%m%d_%H%M%S)
    echo "$log_dir/UpSeller_Network_Check_$timestamp.log"
}

# 可选的DNS刷新
flush_dns_cache() {
    echo ""
    echo "🔄 DNS缓存刷新选项"
    echo "是否要刷新DNS缓存？(需要sudo密码并可能需要等待) [y/N]: "
    read -r response
    
    if [[ "$response" =~ ^[Yy]$ ]]; then
        echo "正在刷新DNS缓存..."
        if sudo dscacheutil -flushcache 2>/dev/null; then
            echo "✓ DNS缓存刷新成功"
        else
            echo "⚠️ DNS缓存刷新失败，继续检测..."
        fi
        
        if sudo killall -HUP mDNSResponder 2>/dev/null; then
            echo "✓ mDNSResponder重启成功"
        else
            echo "⚠️ mDNSResponder重启失败，继续检测..."
        fi
        
        {
            echo ""
            echo "DNS缓存已刷新"
        } >> "$log_file"
    else
        echo "跳过DNS刷新"
        {
            echo ""
            echo "DNS刷新: 已跳过"
        } >> "$log_file"
    fi
}

# 主程序开始
echo ""
echo "===================================================="
echo " UpSeller Domain Network Connectivity Check - 改进版"
echo "===================================================="

# 1. 检查必需命令
echo "[0/5] 检查必需命令..."
check_commands
echo "✓ 所有必需命令都可用"

# 2. 创建日志文件
log_file=$(create_log_file)
if ! touch "$log_file" 2>/dev/null; then
    echo "❌ 无法创建日志文件: $log_file"
    exit 1
fi

echo "✓ 日志文件创建成功: $log_file"

# 要检测的域名列表
domains=("www.upseller.com" "www.upseller.cn" "app.upseller.com" "app.upseller.cn")

# 初始化计数器
total_domains=0
success_count=0
fail_count=0

# 创建日志文件头部
{
    echo "UpSeller Domain Network Check Report"
    echo "===================================================="
    echo "检测时间: $(date)"
    echo "操作系统: $(sw_vers -productName) $(sw_vers -productVersion)"
    echo "计算机名: $(scutil --get ComputerName 2>/dev/null || echo '未知')"
    echo "用户名: $(whoami)"
    echo "日志位置: $log_file"
    echo "===================================================="
    echo ""
} > "$log_file"

# 3. DNS刷新步骤
echo "[1/5] DNS缓存管理..."
flush_dns_cache

# 4. 检查基础网络连通性
echo "[2/5] 检查基础网络连通性..."
{
    echo ""
    echo "基础网络连通性检查:"
    echo "===================================================="
} >> "$log_file"

# 检查多个公共DNS服务器
dns_servers=("8.8.8.8" "1.1.1.1" "114.114.114.114")
internet_available=false

for dns in "${dns_servers[@]}"; do
    echo "检测与 $dns 的连通性..."
    if timeout 10 ping -c 2 "$dns" &> /dev/null; then
        echo "✓ $dns 连通正常"
        {
            echo "$dns: 连通正常"
        } >> "$log_file"
        internet_available=true
        break
    else
        echo "✗ $dns 连通失败"
        {
            echo "$dns: 连通失败"
        } >> "$log_file"
    fi
done

if [ "$internet_available" = false ]; then
    echo "❌ 网络连接不可用，请检查您的网络设置"
    {
        echo "网络状态: 不可用"
    } >> "$log_file"
    exit 1
else
    echo "✓ 网络连接正常"
    {
        echo "网络状态: 正常"
    } >> "$log_file"
fi

# 5. 检查域名连通性
echo "[3/5] 检查域名连通性..."
{
    echo ""
    echo "域名连通性检查结果:"
    echo "===================================================="
} >> "$log_file"

for domain in "${domains[@]}"; do
    ((total_domains++))
    echo ""
    echo "检测域名: $domain"
    {
        echo ""
        echo "域名: $domain"
    } >> "$log_file"
    
    # 解析IP地址
    echo "  正在解析IP地址..."
    domain_ip=$(get_domain_ip "$domain")
    
    if [ -n "$domain_ip" ]; then
        echo "  ✓ IP地址: $domain_ip"
        {
            echo "解析IP: $domain_ip"
        } >> "$log_file"
        
        # Ping测试（带超时）
        echo "  正在进行连通性测试..."
        if timeout 15 ping -c 4 -W 3000 "$domain" &> /dev/null; then
            echo "  ✓ 连通测试: 成功"
            {
                echo "连通状态: 成功"
            } >> "$log_file"
            ((success_count++))
        else
            echo "  ✗ 连通测试: 失败"
            {
                echo "连通状态: 失败"
            } >> "$log_file"
            ((fail_count++))
        fi
    else
        echo "  ✗ DNS解析失败"
        {
            echo "状态: DNS解析失败"
        } >> "$log_file"
        ((fail_count++))
    fi
done

# 6. 对失败域名进行路由跟踪
echo "[4/5] 分析失败的连接..."
{
    echo ""
    echo "失败域名路由跟踪结果:"
    echo "===================================================="
} >> "$log_file"

has_failed_domains=false
for domain in "${domains[@]}"; do
    if ! timeout 10 ping -c 1 -W 3000 "$domain" &> /dev/null; then
        has_failed_domains=true
        echo "正在分析 $domain 的路由..."
        {
            echo ""
            echo "路由跟踪: $domain"
            echo "----------------------------"
        } >> "$log_file"
        
        # 使用timeout防止traceroute挂起
        if ! timeout 60 traceroute -m 15 "$domain" >> "$log_file" 2>&1; then
            {
                echo "路由跟踪超时或失败"
            } >> "$log_file"
        fi
    fi
done

if [ "$has_failed_domains" = false ]; then
    echo "✓ 所有域名连接正常，无需路由分析"
    {
        echo "无失败域名，跳过路由跟踪"
    } >> "$log_file"
fi

# 7. 生成最终报告
echo "[5/5] 生成报告..."

# 计算成功率
if [ "$total_domains" -gt 0 ]; then
    percentage=$((success_count * 100 / total_domains))
else
    percentage=0
fi

{
    echo ""
    echo "===================================================="
    echo "总结报告:"
    echo "检测域名总数: $total_domains"
    echo "成功连接数: $success_count"
    echo "失败连接数: $fail_count"
    echo "成功率: $percentage%"
    echo "===================================================="
    echo ""
    echo "检测完成时间: $(date)"
} >> "$log_file"

# 显示最终结果
echo ""
echo "===================================================="
echo " 检测结果总结"
echo "===================================================="
echo " 检测域名总数: $total_domains"
echo " 成功连接数: $success_count"
echo " 失败连接数: $fail_count"
echo " 成功率: $percentage%"
echo "===================================================="

# 根据结果给出建议
echo ""
if [ "$fail_count" -gt 0 ]; then
    if [ "$success_count" -eq 0 ]; then
        echo "❌ 严重问题: 所有域名都无法连接!"
        echo "   建议检查项目:"
        echo "   1. 检查网络连接状态"
        echo "   2. 验证DNS设置"
        echo "   3. 检查防火墙配置"
        echo "   4. 联系网络管理员"
    else
        echo "⚠️  警告: 部分域名连接失败"
        echo "   请查看日志文件中的详细路由跟踪结果"
        echo "   可能的原因:"
        echo "   1. 特定域名的DNS问题"
        echo "   2. 网络路由问题" 
        echo "   3. 服务器临时不可用"
    fi
else
    echo "✅ 成功: 所有域名连接正常!"
    echo "   网络状态良好，可以正常使用UpSeller服务"
fi

echo ""
echo "📋 详细报告已保存到:"
echo "   $log_file"
echo ""
echo "检测完成! 🎉" 