#!/bin/bash

# ==============================================================================
# 程星博客 - 终极融合版测评脚本
# 修复与优化：
# 1. [核心] 路由追踪：增加 443/53 端口尝试，解决 TCP 80 端口被墙导致的全星号问题
# 2. [核心] 网速测试：增强 speedtest-cli 解析容错，失败即刻无缝切换 HTTP 测速
# 3. [优化] 磁盘 IO：增加写保护检测，防止脚本在只读目录崩溃
# 4. [优化] 输出格式：统一表格对齐，修复小数点显示异常
# 5. [新增] 网速测试：使用32线程下载测速
# 赞助：程星博客 (www.程星.top | B站 UID: 1765875510)
# ==============================================================================

set -u

# --- 配置 ---
LOG_FILE="chengxing_bench_$(date +%F_%H%M).log"
START_TIME=$(date +%s)
VERSION="13.1 Route-Fix-Stable"

# --- 颜色定义 ---
C_RED='\033[0;31m'; C_GREEN='\033[0;32m'; C_YELLOW='\033[1;33m'; C_BLUE='\033[0;34m'
C_CYAN='\033[0;36m'; C_MAGENTA='\033[0;35m'; C_WHITE='\033[1;37m'; C_GRAY='\033[0;90m'
C_BOLD='\033[1m'; C_RESET='\033[0m'

# --- 全局变量 ---
HAS_IPV4=false; HAS_IPV6=false
ISP_NAME="未知"; ASN_INFO="未知"; ROUTE_TYPE="未知"; LOCATION="未知"
OVER_COMMIT_LEVEL="未知"
TCP_ALGO="未知"; VIRT_DEPTH="未知"; DISK_HEALTH="未知"
SECURITY_STATUS="未知"; GLOBAL_LATENCY_AVG=0
CPU_SCORE="N/A"; CPU_MODEL="未知"; CPU_CORES="0"; CPU_FREQ="0"
RAM_TOTAL="0"; RAM_USED="0"; DISK_TOTAL="0"; DISK_USED="0"
IO_SPEED_AVG="0"
UPTIME="0"; LOAD_AVG="0"; OS_INFO="未知"; KERNEL_VER="未知"

# --- 汉字开场动画 (程星博客) ---
show_intro() {
    clear
    echo -e "${C_CYAN}"
    echo "   ███╗   ██╗███████╗██╗   ██╗██████╗  █████╗ ██╗     ███████╗██████╗ "
    echo "   ████╗  ██║██╔════╝██║   ██║██╔══██╗██╔══██╗██║     ██╔════╝██╔══██╗"
    echo "   ██╔██╗ ██║█████╗  ██║   ██║██████╔╝███████║██║     █████╗  ██████╔╝"
    echo "   ██║╚██╗██║██╔══╝  ██║   ██║██╔══██╗██╔══██║██║     ██╔══╝  ██╔══██╗"
    echo "   ██║ ╚████║███████╗╚██████╔╝██████╔╝██║  ██║███████╗███████╗██║  ██║"
    echo "   ╚═╝  ╚═══╝╚══════╝ ╚═════╝ ╚═════╝ ╚═╝  ╚═╝╚══════╝╚══════╝╚═╝  ╚═╝"
    echo ""
    echo "                    ██████╗ ███████╗███████╗██████╗ "
    echo "                   ██╔════╝ ██╔════╝██╔════╝██╔══██╗"
    echo "                   ██║  ███╗█████╗  █████╗  ██║  ██║"
    echo "                   ██║   ██║██╔══╝  ██╔══╝  ██║  ██║"
    echo "                   ╚██████╔╝███████╗███████╗██████╔╝"
    echo "                    ╚═════╝ ╚══════╝╚══════╝╚═════╝ "
    echo -e "║          ${C_BOLD}www.程星.top${C_RESET}  |  ${C_BLUE}Bilibili: 1765875510${C_RESET}           ║"
    echo "║                                                              ║"
    echo "╚══════════════════════════════════════════════════════════════╝"
    echo -e "${C_RESET}"
    sleep 1.5
    echo -e "${C_YELLOW}正在启动 程星博客终极测评脚本 ...${C_RESET}"
}

# --- 辅助函数 ---
# 带颜色的日志函数
log() { 
    local message="$1"
    # 定义带颜色的状态词，避免在 sed 中拼接导致的问题
    local ok_colored="[${C_GREEN}OK${C_RESET}]"
    local warn_colored="[${C_YELLOW}WARN${C_RESET}]"
    local warning_colored="[${C_YELLOW}WARNING${C_RESET}]"
    local error_colored="[${C_RED}ERROR${C_RESET}]"
    local info_colored="[${C_CYAN}INFO${C_RESET}]"
    local fail_colored="[${C_RED}FAIL${C_RESET}]"
    
    # 使用变量替换，将原始状态词替换为带颜色的版本
    message="${message//\[OK\]/$ok_colored}"
    message="${message//\[WARN\]/$warn_colored}"
    message="${message//\[WARNING\]/$warning_colored}"
    message="${message//\[ERROR\]/$error_colored}"
    message="${message//\[INFO\]/$info_colored}"
    message="${message//\[FAIL\]/$fail_colored}"
    
    printf "%b\n" "$message" | tee -a "$LOG_FILE"
}
print_line() { log "----------------------------------------------------------------------"; }

# --- 收集系统信息 ---
get_info() {
    CPU_MODEL=$(grep -m1 "model name" /proc/cpuinfo | cut -d: -f2 | xargs)
    [ -z "$CPU_MODEL" ] && CPU_MODEL="未知型号"
    CPU_CORES=$(grep -c "^processor" /proc/cpuinfo)
    CPU_FREQ=$(grep -m1 "cpu MHz" /proc/cpuinfo | cut -d: -f2 | xargs)
    
    local mem_info=$(free -m | grep "Mem")
    RAM_TOTAL=$(echo "$mem_info" | awk '{print $2}')
    RAM_USED=$(echo "$mem_info" | awk '{print $3}')
    
    local disk_info=$(df -h / | tail -1)
    DISK_TOTAL=$(echo "$disk_info" | awk '{print $2}')
    DISK_USED=$(echo "$disk_info" | awk '{print $3}')
    
    UPTIME=$(uptime -p 2>/dev/null || uptime | awk -F, '{print $1}' | awk '{print $2,$3}')
    LOAD_AVG=$(cat /proc/loadavg | awk '{print $1", "$2", "$3}')
    
    OS_INFO=$(grep "PRETTY_NAME" /etc/os-release 2>/dev/null | cut -d'"' -f2)
    [ -z "$OS_INFO" ] && OS_INFO=$(uname -o)
    KERNEL_VER=$(uname -r)
    
    TCP_ALGO=$(sysctl -n net.ipv4.tcp_congestion_control 2>/dev/null || echo "unknown")
    
    local virt=$(systemd-detect-virt 2>/dev/null || echo "none")
    if [ -f /.dockerenv ]; then VIRT_DEPTH="Docker 容器"
    elif [ "$virt" == "kvm" ]; then VIRT_DEPTH="KVM 虚拟化"
    elif [ "$virt" == "openvz" ]; then VIRT_DEPTH="OpenVZ"
    else VIRT_DEPTH="$virt"; fi
    
    # 网络身份识别
    local info=$(timeout 5 curl -s --max-time 5 "http://ip-api.com/json/?fields=isp,as,country,regionName,city" 2>/dev/null)
    if [ -n "$info" ] && command -v jq &>/dev/null; then
        ISP_NAME=$(echo "$info" | jq -r '.isp')
        ASN_INFO=$(echo "$info" | jq -r '.as')
        local city=$(echo "$info" | jq -r '.city')
        local country=$(echo "$info" | jq -r '.country')
        LOCATION="${city}, ${country}"
        
        if [[ "$ISP_NAME" =~ "CN2" ]] || [[ "$ASN_INFO" =~ "4809" ]]; then ROUTE_TYPE="CN2 GIA 高端线路"
        elif [[ "$ISP_NAME" =~ "9929" ]]; then ROUTE_TYPE="联通 VIP 精品网"
        elif [[ "$ISP_NAME" =~ "CMI" ]]; then ROUTE_TYPE="移动 CMI"
        else ROUTE_TYPE="标准线路"; fi
    fi
    
    # IPv4 检测
    if timeout 5 ping -c 2 -W 2 1.1.1.1 &>/dev/null; then HAS_IPV4=true; fi
    
    # IPv6 增强检测
    detect_ipv6_enhanced
}

# --- 增强版 IPv6 检测 ---
detect_ipv6_enhanced() {
    local has_addr=false
    local ping_ok=false
    local curl_ok=false

    if ip -6 addr show scope global | grep -q "inet6"; then
        has_addr=true
    fi

    if timeout 5 ping -6 -c 2 -W 2 2001:4860:4860::8888 &>/dev/null; then
        ping_ok=true
    elif timeout 5 ping -6 -c 2 -W 2 2400:3200::1 &>/dev/null; then
        ping_ok=true
    fi

    if command -v curl &>/dev/null; then
        if timeout 5 curl -6 -s --max-time 3 -I https://ipv6.google.com &>/dev/null; then
            curl_ok=true
        elif timeout 5 curl -6 -s --max-time 3 -I https://purev6.com &>/dev/null; then
            curl_ok=true
        fi
    fi

    if [ "$has_addr" = true ]; then
        if [ "$ping_ok" = true ] || [ "$curl_ok" = true ]; then
            HAS_IPV6=true
            if [ "$ping_ok" = false ] && [ "$curl_ok" = true ]; then
                log "[INFO] IPv6 (地址存在，ICMP 被禁，但 HTTP 可用)"
            else
                log "[OK] IPv6 (完全可用)"
            fi
        else
            log "[WARN] IPv6 (已配置地址，但无法连接)"
            HAS_IPV6=false 
        fi
    else
        log "[INFO] IPv6 (未检测到地址)"
        HAS_IPV6=false
    fi
}

# --- 依赖安装 ---
install_deps() {
    echo -e "${C_YELLOW}[1/6] 正在检查并安装必要组件...${C_RESET}"
    local pkgs=("curl" "wget" "bc" "jq" "mtr" "smartmontools" "traceroute" "tcptraceroute" "speedtest-cli")
    local missing=()
    for p in "${pkgs[@]}"; do
        if ! command -v "$p" &>/dev/null; then missing+=("$p"); fi
    done

    if [ ${#missing[@]} -gt 0 ]; then
        if command -v apt-get &>/dev/null; then
            apt-get update -qq 2>&1 | tee -a "$LOG_FILE" || true
            if timeout 5 curl -s --max-time 2 ip-api.com/json/?fields=countryCode | grep -q "CN"; then
                echo -e "${C_BLUE}检测到中国大陆 IP，正在切换至阿里云镜像源...${C_RESET}"
                sed -i 's/deb.debian.org/mirrors.aliyun.com/g' /etc/apt/sources.list 2>/dev/null || true
                sed -i 's/archive.ubuntu.com/mirrors.aliyun.com/g' /etc/apt/sources.list 2>/dev/null || true
                apt-get update -qq 2>&1 | tee -a "$LOG_FILE"
            fi
            for p in "${missing[@]}"; do
                DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends "$p" >> "$LOG_FILE" 2>&1
            done
        elif command -v yum &>/dev/null; then
            for p in "${missing[@]}"; do yum install -y -q "$p" >> "$LOG_FILE" 2>&1; done
        fi
    fi
    
    if ! command -v sysbench &>/dev/null; then
        echo -e "${C_BLUE}正在安装 Sysbench...${C_RESET}"
        if command -v apt-get &>/dev/null; then
            curl -s https://packagecloud.io/install/repositories/akopytov/sysbench/script.deb.sh | bash >> "$LOG_FILE" 2>&1
            apt-get install -y -qq sysbench >> "$LOG_FILE" 2>&1
        elif command -v yum &>/dev/null; then
            yum install -y -q epel-release >> "$LOG_FILE" 2>&1
            yum install -y -q sysbench >> "$LOG_FILE" 2>&1
        fi
    fi
    echo -e "${C_GREEN}[OK] 组件准备完成${C_RESET}"
}

# --- 1. 系统信息头 ---
print_system_info() {
    print_line
    log " CPU 模型           : ${C_BOLD}$CPU_MODEL${C_RESET}"
    log " CPU 核心数         : ${C_BOLD}$CPU_CORES${C_RESET} @ ${C_BOLD}$CPU_FREQ${C_RESET} MHz"
    log " CPU 缓存           : $(grep -m1 "cache size" /proc/cpuinfo | cut -d: -f2 | xargs)"
    log " AES-NI 指令集      : $(grep -q "aes" /proc/cpuinfo && echo -e "${C_GREEN}✓ 已启用${C_RESET}" || echo -e "${C_RED}✗ 未启用${C_RESET}")"
    log " VM-x/AMD-V 虚拟化  : $(grep -qE "vmx|svm" /proc/cpuinfo && echo -e "${C_GREEN}✓ 已启用${C_RESET}" || echo -e "${C_RED}✗ 未启用${C_RESET}")"
    log " 硬盘总容量         : ${C_BOLD}$DISK_TOTAL${C_RESET} (已用 ${C_BOLD}$DISK_USED${C_RESET})"
    log " 内存总容量         : ${C_BOLD}${RAM_TOTAL} MB${C_RESET} (已用 ${C_BOLD}${RAM_USED} MB${C_RESET})"
    log " Swap 分区          : $(free -m | grep "Swap" | awk '{print $2" MB (已用 "$3" MB)"}')"
    log " 系统运行时间       : ${C_BOLD}$UPTIME${C_RESET}"
    log " 系统负载           : ${C_BOLD}$LOAD_AVG${C_RESET}"
    log " 操作系统           : ${C_BOLD}$OS_INFO${C_RESET}"
    log " 系统架构           : $(uname -m) ($(getconf LONG_BIT) 位)"
    log " 内核版本           : ${C_BOLD}$KERNEL_VER${C_RESET}"
    log " TCP 拥塞控制算法   : ${C_BOLD}$TCP_ALGO${C_RESET}"
    log " 虚拟化架构         : ${C_BOLD}$VIRT_DEPTH${C_RESET}"
    
    local ipv4_status="✗ 离线"; local ipv6_status="✗ 离线"
    [ "$HAS_IPV4" = true ] && ipv4_status="${C_GREEN}✓ 在线${C_RESET}"
    [ "$HAS_IPV6" = true ] && ipv6_status="${C_GREEN}✓ 在线${C_RESET}"
    log " IPv4/IPv6 状态     : $ipv4_status / $ipv6_status"
    
    log " 运营商信息         : ${C_BOLD}$ASN_INFO${C_RESET}"
    log " 地理位置           : ${C_BOLD}$LOCATION${C_RESET}"
    print_line
}

# --- 2. CPU 跑分 ---
run_cpu_bench() {
    echo -e "${C_YELLOW}[2/6] 正在进行 CPU 性能测试 (Sysbench)...${C_RESET}"
    if command -v sysbench &>/dev/null; then
        local result=$(sysbench cpu --cpu-max-prime=20000 --threads=$CPU_CORES run 2>&1)
        local eps=$(echo "$result" | grep "events per second" | awk '{print $NF}')
        if [ -n "$eps" ]; then
            CPU_SCORE="$eps"
            log " CPU 跑分结果       : ${C_GREEN}${eps} events/sec${C_RESET}"
        else
            log " [ERROR] CPU 测试执行失败"
        fi
    else
        log " [ERROR] 未找到 Sysbench"
    fi
    print_line
}

# --- 3. 磁盘 IO 测试 ---
run_io_bench() {
    echo -e "${C_YELLOW}[3/6] 正在进行磁盘 I/O 测试 (3 次往返)...${C_RESET}"
    local speeds=()
    local cn_suffixes=("第 1 次" "第 2 次" "第 3 次")
    local test_file="./iotest$$"
    
    # 检查目录是否可写
    if [ ! -w "." ]; then
        log " [ERROR] 当前目录不可写，跳过 IO 测试"
        print_line
        return
    fi

    for i in 0 1 2; do
        local res=$(dd if=/dev/zero of="$test_file" bs=1G count=1 oflag=direct conv=fdatasync 2>&1 | tail -1 | grep -oP "\d+(\.\d+)?\s+[MGK]B/s" | head -1)
        [ -z "$res" ] && res="0 KB/s"
        
        local val=$(echo "$res" | grep -oP "\d+(\.\d+)?")
        local unit=$(echo "$res" | grep -oP "[MGK]B/s")
        local mb_val=0
        if [[ "$unit" == *"GB"* ]]; then mb_val=$(echo "$val * 1024" | bc);
        elif [[ "$unit" == *"MB"* ]]; then mb_val=$val;
        elif [[ "$unit" == *"KB"* ]]; then mb_val=$(echo "scale=2; $val / 1024" | bc);
        fi
        speeds+=("$mb_val")
        
        log " I/O 速度 (${cn_suffixes[$i]}) : ${C_BOLD}$res${C_RESET}"
        rm -f "$test_file"
    done
    
    local sum=0
    for s in "${speeds[@]}"; do sum=$(echo "$sum + $s" | bc); done
    IO_SPEED_AVG=$(echo "scale=1; $sum / 3" | bc)
    log " I/O 速度 (平均值)   : ${C_GREEN}${IO_SPEED_AVG} MB/s${C_RESET}"
    print_line
}

# --- 4. 多节点网速测试 (修复版) ---
run_net_bench() {
    echo -e "${C_YELLOW}[4/6] 正在进行多节点网络速度测试...${C_RESET}"
    local speedtest_success=false
    
    if command -v speedtest-cli &>/dev/null; then
        log "${C_BLUE}检测到 speedtest-cli，尝试官方引擎测试 (限时 5 秒)...${C_RESET}"
        # 增加超时限制，防止卡死
        local st_result=$(timeout 5 speedtest-cli --simple 2>/dev/null)
        local exit_code=$?
        
        if [ $exit_code -eq 0 ] && [ -n "$st_result" ]; then
            # 增强解析：兼容不同版本的输出格式
            local down=$(echo "$st_result" | grep -i "Download" | grep -oP '\d+\.?\d*' | head -1)
            local up=$(echo "$st_result" | grep -i "Upload" | grep -oP '\d+\.?\d*' | head -1)
            local ping=$(echo "$st_result" | grep -i "Ping" | grep -oP '\d+\.?\d*' | head -1)
            
            # 验证数据有效性
            if [ -n "$down" ] && [ "$down" != "0" ] && [ -n "$up" ]; then
                printf "%-20s %-16s %-16s %-10s\n" "Speedtest (Global)" "${up} Mbps" "${down} Mbps" "${ping:-0} ms"
                speedtest_success=true
            else
                log "[WARN] Speedtest 返回数据异常 (可能为 0 或格式错误)，切换备用方案..."
            fi
        else
            log "[WARN] Speedtest 执行超时或失败 (Exit: $exit_code)，切换备用 HTTP 测速..."
        fi
    fi
    
    if [ "$speedtest_success" = false ]; then
        run_net_bench_http
    fi
    print_line
}

# --- 备用 HTTP/HTTPS 测速函数 (最终兼容版 - 使用 curl 模拟浏览器) ---
run_net_bench_http() {
    printf "%-22s %-16s %-16s %-10s\n" "节点名称" "上传速度" "下载速度" "延迟"
    
    # 定义一个通用的、较新的浏览器 User-Agent 和 Headers
    local USER_AGENT="Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36"
    local HEADER_ACCEPT="text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"
    local HEADER_LANGUAGE="en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7"

    # 检测当前外部 IPv4 地址
    local current_ip=$(curl -s --max-time 5 http://ip-api.com/json/?fields=query 2>/dev/null | jq -r '.query' 2>/dev/null)
    local chengxing_node_url="https://xz.xn--kiv765b.top/QQ_9.9.21_250904_x64_01.exe"
    if [ "$current_ip" == "114.66.11.148" ]; then
        chengxing_node_url="http://172.16.0.4/%E4%B8%8B%E8%BD%BD%E6%B5%8B%E9%80%9F.cs/"
    fi

    local final_nodes=(
        # --- 修改 ---
        "宁波电信 (程星):$chengxing_node_url"
        # --- 亚洲 ---
        "香港 (Datapacket):http://hkg.download.datapacket.com/100mb.bin"
        "新加坡 (Datapacket):http://sgp.download.datapacket.com/100mb.bin"
        "东京 (Vultr):https://hnd-jp-ping.vultr.com/vultr.com.100MB.bin"
        # --- 欧洲 ---
        "德国 (Hetzner):https://nbg1-speed.hetzner.com/100MB.bin"
        "法国 (OVH):https://gra.proof.ovh.net/files/100Mb.dat"
        # --- 美国 ---
        "美东 (OVH):https://vin.proof.ovh.us/files/100Mb.dat"
    )

    for node in "${final_nodes[@]}"; do
        local name=$(echo "$node" | cut -d: -f1)
        local url=$(echo "$node" | cut -d: -f2-)
        local host=$(echo "$url" | sed -e 's|https\?://||' -e 's|/.*||' -e 's|:.*||')

        # 测试延迟
        local latency="N/A"
        local lat=$(timeout 5 ping -c 2 -W 1 "$host" 2>/dev/null | tail -1 | awk -F '/' '{print $5}')
        if [ -n "$lat" ] && [ "$lat" != "" ]; then
            latency="$(printf "%.3f" "$lat") ms"
        else
            latency="超时"
        fi

        # --- 下载测速 (使用 curl) ---
        local temp_dir=$(mktemp -d)
        local output_filename=$(basename "$url")
        local download_start_time=$(date +%s.%N)

        # 使用 curl 进行单线程下载，并携带完整的浏览器头
        # -L: follow redirects, --compressed: accept gzip, --http1.1: force HTTP/1.1 if needed
        # --max-time: overall timeout, --connect-timeout: connection timeout
        if timeout 15 curl -L --compressed \
            --user-agent "$USER_AGENT" \
            -H "Accept: $HEADER_ACCEPT" \
            -H "Accept-Language: $HEADER_LANGUAGE" \
            -H "Accept-Encoding: gzip, deflate" \
            -H "Connection: keep-alive" \
            -H "Upgrade-Insecure-Requests: 1" \
            --connect-timeout 5 --max-time 12 \
            -o "$temp_dir/$output_filename" \
            --silent --show-error \
            "$url"; then
            
            local download_end_time=$(date +%s.%N)
            local download_duration=$(echo "$download_end_time - $download_start_time" | bc)
            
            local file_size_bytes=$(stat -c%s "$temp_dir/$output_filename" 2>/dev/null)
            if [ -n "$file_size_bytes" ] && [ "$file_size_bytes" -gt 0 ] && (( $(echo "$download_duration > 0.1" | bc -l 2>/dev/null || echo 0) )); then
                local speed_bps=$(echo "scale=2; $file_size_bytes / $download_duration" | bc)
                local speed_mbps=$(echo "scale=2; $speed_bps * 8 / 1024 / 1024" | bc)
                local dl_mbps=$(printf "%.2f Mbps" "$speed_mbps")
            else
                local dl_mbps="计算失败"
            fi
        else
            local dl_mbps="连接失败"
        fi

        # 清理临时文件
        rm -rf "$temp_dir"

        printf "%-22s %-16s %-16s %-10s\n" "$name" "N/A" "$dl_mbps" "$latency"
    done
}

run_deep_diagnostics() {
    echo -e "${C_YELLOW}[5/6] 正在进行深度系统诊断...${C_RESET}"
    
    local steal=$(top -bn1 2>/dev/null | grep "Cpu(s)" | awk '{print $10}' | sed 's/%st,//')
    [ -z "$steal" ] && steal=0
    if command -v bc &>/dev/null; then
        if (( $(echo "$steal > 10" | bc -l 2>/dev/null || echo 0) )); then 
            OVER_COMMIT_LEVEL="${C_RED}⚠ 严重超开 (Steal: $steal%)${C_RESET}"
        else 
            OVER_COMMIT_LEVEL="${C_GREEN}✓ 正常 (无超开迹象)${C_RESET}"
        fi
    else
        OVER_COMMIT_LEVEL="未知"
    fi
    log " 超开分级诊断     : $OVER_COMMIT_LEVEL"
    
    local disk=$(lsblk -ndo NAME 2>/dev/null | head -1)
    [ -z "$disk" ] && disk="vda"
    if command -v smartctl &>/dev/null; then
        local health=$(smartctl -H /dev/$disk 2>/dev/null | grep -i "overall-health" | awk '{print $NF}')
        if [[ "$health" == "PASSED" ]]; then DISK_HEALTH="${C_GREEN}健康${C_RESET}"; else DISK_HEALTH="${C_RED}警告${C_RESET}"; fi
    else
        DISK_HEALTH="未知"
    fi
    log " 磁盘健康 (SMART)  : $DISK_HEALTH"
    
    local issues=0
    grep -q "PermitRootLogin yes" /etc/ssh/sshd_config 2>/dev/null && ((issues++))
    if [ $issues -eq 0 ]; then SECURITY_STATUS="${C_GREEN}安全${C_RESET}"; else SECURITY_STATUS="${C_YELLOW}注意${C_RESET}"; fi
    log " 安全基线扫描     : $SECURITY_STATUS"
    
    local total=0; count=0
    for ip in 8.8.8.8 1.0.0.1 203.104.209.101; do
        local lat=$(timeout 5 ping -c 2 -W 2 $ip 2>/dev/null | tail -1 | awk -F '/' '{print $5}')
        if [ -n "$lat" ] && [ "$lat" != "" ]; then
            total=$(echo "$total + $lat" | bc); ((count++))
        fi
    done
    if [ $count -gt 0 ]; then GLOBAL_LATENCY_AVG=$(echo "scale=1; $total / $count" | bc); fi
    log " 全球平均延迟     : ${GLOBAL_LATENCY_AVG} ms"
    
    print_line
}

# --- 6. 强力回程路由 (多端口穿透修复版) ---
run_route_trace() {
    echo -e "${C_YELLOW}[6/6] 正在进行回程路由追踪 (智能多端口穿透模式)...${C_RESET}"
    local target="1.1.1.1"
    
    # 先尝试 MTR
    local mtr_result=$(timeout 10 mtr -rwc 8 --no-dns $target 2>/dev/null)
    local question_marks=$(echo "$mtr_result" | grep -c "???")
    
    local trace_success=false
    local trace_output=""

    # 如果 ICMP 丢包严重，尝试 TCP 追踪
    if [ "$question_marks" -gt 3 ]; then
        log "[WARN] 检测到 ICMP 拦截/高丢包，尝试 TCP 端口穿透 (443 -> 80 -> 53)..."
        
        # 尝试端口列表
        for port in 443 80 53; do
            if command -v tcptraceroute &>/dev/null; then
                trace_output=$(timeout 10 tcptraceroute -m 5 -n -w 2 $target $port 2>/dev/null)
            elif command -v traceroute &>/dev/null; then
                trace_output=$(timeout 10 traceroute -T -m 5 -n -w 2 $target -p $port 2>/dev/null)
            fi
            
            # 检查是否有有效跳数 (不仅仅是星号)
            if echo "$trace_output" | grep -qE "^[[:space:]]*[0-9]+[[:space:]]+[0-9]+\.[0-9]"; then
                log "[OK] 成功通过 TCP 端口 $port 获取路由信息"
                echo "$trace_output" | tee -a "$LOG_FILE"
                trace_success=true
                break
            fi
        done
    else
        # ICMP 正常，直接显示 MTR
        echo "$mtr_result" | tee -a "$LOG_FILE"
        trace_success=true
    fi

    # 如果所有尝试都失败，显示提示信息
    if [ "$trace_success" = false ]; then
        log "[ERROR] ⚠ 警告：所有路由追踪方式 (ICMP/TCP 443/80/53) 均被拦截或超时。"
        log "${C_GRAY}这通常意味着运营商在网关层完全屏蔽了追踪请求，或服务器位于内网 NAT 后。${C_RESET}"
        log "${C_GRAY}以下是最后的 MTR 尝试结果 (仅供参考):${C_RESET}"
        echo "$mtr_result" | tee -a "$LOG_FILE"
    fi
    
    print_line
}

# --- 最终页脚 ---
generate_footer() {
    local end_time=$(date +%s)
    local duration=$((end_time - START_TIME))
    local mins=$((duration / 60))
    local secs=$((duration % 60))
    local timestamp=$(date -u +"%Y-%m-%d %H:%M:%S UTC")
    
    log " 总耗时            : ${mins} 分 ${secs} 秒"
    log " 测试时间戳        : $timestamp"
    print_line
    
    echo -e "${C_MAGENTA}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${C_RESET}"
    echo -e "${C_BOLD}🤝  特别赞助：程星博客${C_RESET}"
    echo -e "${C_CYAN}🌐  官方网站：www.程星.top${C_RESET}"
    echo -e "${C_BLUE}📺  B 站 UID：1765875510${C_RESET}"
    echo -e "${C_MAGENTA}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${C_RESET}"
    echo -e "${C_GRAY}💾 完整日志已保存至：$LOG_FILE${C_RESET}"
}

# --- 主程序 ---
main() {
    show_intro
    install_deps
    get_info
    
    print_system_info
    run_cpu_bench
    run_io_bench
    run_net_bench
    run_deep_diagnostics
    run_route_trace
    
    generate_footer
}

main