#!/bin/bash

# 采样间隔(秒)
INTERVAL=2

# 获取 TCP 统计数据的函数
# /proc/net/snmp 中 Tcp 行的第 12 列是 OutSegs (发送数)，第 13 列是 RetransSegs (重传数)
get_tcp_stats() {
    cat /proc/net/snmp | grep "^Tcp: " | awk 'NR==2 {print $12 " " $13}'
}

echo "----------------------------------------------------------------"
echo "正在监控 TCP 重传率 (每 ${INTERVAL} 秒刷新, 按 Ctrl+C 停止)"
echo "数据来源: /proc/net/snmp (对应 netstat -s)"
echo "----------------------------------------------------------------"
printf "%-10s | %-15s | %-15s | %-10s\n" "时间" "发送包数(Delta)" "重传包数(Delta)" "重传率(%)"
echo "----------------------------------------------------------------"

# 1. 获取初始值
read old_out old_retrans <<< $(get_tcp_stats)

while true; do
    # 2. 等待
    sleep $INTERVAL

    # 3. 获取新值
    read new_out new_retrans <<< $(get_tcp_stats)

    # 4. 计算差值 (Delta)
    delta_out=$((new_out - old_out))
    delta_retrans=$((new_retrans - old_retrans))

    # 5. 计算重传率 (处理除以0的情况)
    if [ "$delta_out" -eq 0 ]; then
        rate=0
    else
        # 使用 awk 进行浮点数运算，保留4位小数
        rate=$(awk -v r=$delta_retrans -v o=$delta_out 'BEGIN { printf "%.4f", (r * 100 / o) }')
    fi

    # 6. 打印结果
    timestamp=$(date +"%H:%M:%S")

    # 如果重传率超过 1%，用红色高亮显示
    if (( $(echo "$rate > 1.0" | bc -l) )); then
         printf "%-10s | %-15d | %-15d | \033[31m%-10s\033[0m\n" "$timestamp" "$delta_out" "$delta_retrans" "${rate}%"
    else
         printf "%-10s | %-15d | %-15d | %-10s\n" "$timestamp" "$delta_out" "$delta_retrans" "${rate}%"
    fi

    # 7. 更新旧值，准备下一次循环
    old_out=$new_out
    old_retrans=$new_retrans
done
