#!/bin/bash

# 获取网卡列表
declare -a interfaces
interfaces=( $(ls /sys/class/net) )

# 让用户选择网卡
echo "可用的网卡列表:"
for i in "${!interfaces[@]}"; do
    echo "$i: ${interfaces[$i]}"
done

echo -n "请选择网卡编号: "
read iface_index

# 确保用户输入有效
test -n "${interfaces[$iface_index]}" || { echo "无效的选择"; exit 1; }
iface=${interfaces[$iface_index]}

# 获取队列
echo "获取 $iface 的队列..."
tx_queues=( $(ls /sys/class/net/$iface/queues/ | grep tx-) )
rx_queues=( $(ls /sys/class/net/$iface/queues/ | grep rx-) )

echo "$iface 共有 ${#rx_queues[@]} 个 RX 队列，${#tx_queues[@]} 个 TX 队列"

echo -n "确认修改所有队列的 RPS 和 XPS? (y/n): "
read confirm_all

if [ "$confirm_all" = "y" ]; then
    for queue in "${rx_queues[@]}"; do
        rps_file="/sys/class/net/$iface/queues/$queue/rps_cpus"
        if [ -f "$rps_file" ]; then
            format=$(cat $rps_file)
            new_rps=$(echo "$format" | sed 's/[0-9a-fA-F]/f/g')
            echo "$queue RPS CPU 绑定格式: $format"
            echo "$queue 新的 RPS CPU 绑定值: $new_rps"
            echo "$new_rps" | sudo tee $rps_file > /dev/null
            echo "已设置 $queue RPS CPU: $new_rps"
        fi
    done

    for queue in "${tx_queues[@]}"; do
        xps_file="/sys/class/net/$iface/queues/$queue/xps_cpus"
        if [ -f "$xps_file" ]; then
            format=$(cat $xps_file)
            new_xps=$(echo "$format" | sed 's/[0-9a-fA-F]/f/g')
            echo "$queue XPS CPU 绑定格式: $format"
            echo "$queue 新的 XPS CPU 绑定值: $new_xps"
            echo "$new_xps" | sudo tee $xps_file > /dev/null
            echo "已设置 $queue XPS CPU: $new_xps"
        fi
    done
else
    echo "跳过修改 RPS 和 XPS CPU 绑定值"
fi

echo "配置完成!"

# 直接覆盖 sysctl 配置
echo "更新 sysctl.conf..."
cat > /etc/sysctl.conf << EOF
net.ipv4.ip_forward = 1
net.netfilter.nf_conntrack_max = 999999999
net.nf_conntrack_max = 999999999
net.netfilter.nf_conntrack_buckets = 194857600
net.netfilter.nf_conntrack_icmp_timeout = 10
net.netfilter.nf_conntrack_tcp_timeout_syn_recv = 5
net.netfilter.nf_conntrack_tcp_timeout_syn_sent = 5
net.netfilter.nf_conntrack_tcp_timeout_established = 600
net.netfilter.nf_conntrack_tcp_timeout_fin_wait = 10
net.netfilter.nf_conntrack_tcp_timeout_time_wait = 10
net.netfilter.nf_conntrack_tcp_timeout_close_wait = 10
net.netfilter.nf_conntrack_tcp_timeout_last_ack = 10
EOF

# 使 sysctl 配置生效
echo "应用 sysctl 配置..."
sudo sysctl -p

echo "sysctl 配置更新完成!"