#!/bin/bash
# Debian 12 CDN边缘节点 - 20G bond0+64G 内存 终极修复版V4
# 特点：tcp_mem最大4GB、tcp_rmem/wmem优化、bond0物理成员网卡队列硬设、静默输出+容错
# 修复点：硬件Offload/队列配置作用于bond0的物理成员网卡，而非bond0虚拟接口
set -uo pipefail
trap 'echo -e "\n❌ 脚本执行出错：$0:$LINENO"; exit 1' ERR

# 固化配置
LOG_FILE="/var/log/cdn_bond0_20g.log"
BACKUP_DIR="/etc/cdn_bond0_20g_backup_$(date +%F_%H%M%S)"
TARGET_IFACE="bond0"

# 初始化&Root校验
exec > >(tee -a "$LOG_FILE") 2>&1
[[ $EUID -ne 0 ]] && echo "❌ 必须root运行" && exit 1

echo -n "🔧 检测bond0网卡..."
if ! ip link show "$TARGET_IFACE" >/dev/null 2>&1; then
    echo -e "\n❌ 未检测到$TARGET_IFACE网卡，请确认名称后修改脚本"
    exit 1
fi
echo "存在"

echo -n "🔧 初始化环境..."
mkdir -p "$BACKUP_DIR"
echo "完成"

echo -n "🔧 关闭无用服务..."
for svc in avahi-daemon cups bluetooth ModemManager wpa_supplicant; do
  systemctl is-active --quiet "$svc" && systemctl disable --now "$svc" >/dev/null 2>&1
done
echo "完成"

echo -n "🔧 禁用SWAP..."
cp -f /etc/fstab "$BACKUP_DIR/fstab.bak"
swapoff -a >/dev/null 2>&1 || true
sed -i.bak '/^[^#]*\bswap\b/s/^/#/' /etc/fstab && mv /etc/fstab.bak "$BACKUP_DIR/"
systemctl mask swap.target >/dev/null 2>&1 && systemctl daemon-reload >/dev/null 2>&1
echo "完成"

echo -n "🔧 配置CPU性能模式..."
apt update -y >/dev/null 2>&1
dpkg -l | grep -q cpufrequtils || apt install -y cpufrequtils >/dev/null 2>&1
if [[ -f /etc/default/cpufrequtils ]]; then
  cp /etc/default/cpufrequtils "$BACKUP_DIR/"
  echo 'GOVERNOR="performance"' > /etc/default/cpufrequtils
  systemctl restart cpufrequtils >/dev/null 2>&1
fi
echo "完成"

echo -n "🔧 配置IRQ均衡..."
apt install -y irqbalance ethtool >/dev/null 2>&1
systemctl enable --now irqbalance >/dev/null 2>&1
echo "完成"

echo -n "🔧 配置网络核心参数..."
cp -f /etc/sysctl.d/99-*.conf "$BACKUP_DIR/" 2>/dev/null || true
rm -f /etc/sysctl.d/99-bbr*.conf /etc/sysctl.d/99-cdn-*.conf
cat >/etc/sysctl.d/99-cdn-bond0-20g.conf <<'EOF'
net.core.default_qdisc = fq_codel
net.ipv4.tcp_congestion_control = bbr
net.ipv6.tcp_congestion_control = bbr

net.ipv4.tcp_slow_start_after_idle = 0
net.ipv4.tcp_no_metrics_save = 1
net.ipv4.tcp_reordering = 32
net.ipv4.tcp_fin_timeout = 6

# 缓冲区优化
net.core.rmem_max = 536870912
net.core.wmem_max = 536870912
net.core.rmem_default = 33554432
net.core.wmem_default = 33554432
net.ipv4.tcp_rmem = 4096 16777216 268435456
net.ipv4.tcp_wmem = 4096 16777216 268435456

# 64G内存专属tcp_mem
net.ipv4.tcp_mem = 524288 1048576 4194304

# CDN高并发backlog
net.core.netdev_max_backlog = 500000
net.core.somaxconn = 131072
net.ipv4.tcp_max_syn_backlog = 262144
net.ipv4.tcp_max_tw_buckets = 2000000
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_timestamps = 1

# TCP Fast Open
net.ipv4.tcp_fastopen = 3

# IPv6固定公网
net.ipv6.conf.all.forwarding = 0
net.ipv6.conf.default.forwarding = 0
net.ipv6.conf.all.accept_ra = 0
net.ipv6.conf.default.accept_ra = 0
net.ipv6.conf.bond0.accept_ra = 0
net.ipv6.conf.all.autoconf = 0
net.ipv6.conf.default.autoconf = 0
net.ipv6.conf.bond0.autoconf = 0
net.ipv6.conf.all.dad_transmits = 1
net.ipv6.conf.default.dad_transmits = 1
net.ipv6.conf.all.accept_redirects = 0
net.ipv6.conf.default.accept_redirects = 0

# 基础防护
net.ipv4.tcp_syncookies = 1
net.ipv4.icmp_echo_ignore_broadcasts = 1
net.ipv4.icmp_ignore_bogus_error_responses = 1
net.ipv4.tcp_retries2 = 6
net.ipv4.tcp_keepalive_time = 600
net.ipv4.tcp_keepalive_intvl = 30
net.ipv4.tcp_keepalive_probes = 10

net.ipv4.conf.bond0.rp_filter = 0
net.ipv4.conf.all.rp_filter = 0
net.core.optmem_max = 65536
EOF
sysctl --system >/dev/null 2>&1
echo "完成"

echo -n "🔧 配置bond0成员网卡硬件Offload..."
# 容错处理：先获取bond0的物理成员网卡列表
BOND_MEMBERS=$(grep -oP 'Slave Interface: \K\w+' /proc/net/bonding/bond0 2>/dev/null)

if [ -z "$BOND_MEMBERS" ]; then
    echo -e "\n⚠️  未检测到bond0的物理成员网卡，跳过硬件配置"
else
    # 遍历所有物理成员网卡执行硬件优化
    for PHY_IFACE in $BOND_MEMBERS; do
        echo -n " [$PHY_IFACE]"
        # 禁用Wake-on-LAN
        ethtool -s "$PHY_IFACE" wol d >/dev/null 2>&1 || true
        # 启用必要的Offload特性
        ethtool -K "$PHY_IFACE" gro on gso on tso on tx-checksum on rx-checksum on >/dev/null 2>&1 || true
        # 禁用LRO（大接收卸载，高并发下易出问题）
        ethtool -K "$PHY_IFACE" lro off >/dev/null 2>&1 || true
        # 禁用网卡中断均衡（交给irqbalance处理）
        ethtool -A "$PHY_IFACE" rx off tx off >/dev/null 2>&1 || true
        # 可选：硬设队列16个（适配X520/X722，可注释禁用）
        ethtool -L "$PHY_IFACE" combined 16 >/dev/null 2>&1 || true
    done
    echo ""
fi

# 仅对bond0做状态确认（无硬件操作）
if ethtool -i "$TARGET_IFACE" >/dev/null 2>&1; then
    echo "✅ bond0成员网卡硬件配置完成（Offload & 队列硬设）"
else
    echo "⚠️  bond0状态检测异常，但成员网卡配置已执行（如有）"
fi

echo -e "\n✅ CDN边缘节点（20G+bond0+64G）优化V4完成"
echo "📜 日志：$LOG_FILE"
echo "📦 配置备份：$BACKUP_DIR"
echo "💡 建议：reboot 彻底生效"