#!/bin/bash

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

# 让用户选择操作模式
echo "请选择操作模式:"
echo "1: 配置单个网卡"
echo "2: 配置所有网卡"
echo -n "请选择操作模式 (1/2): "
read operation_mode

if [ "$operation_mode" = "1" ]; then
    # 单个网卡模式
    echo "可用的网卡列表:"
    for i in "${!interfaces[@]}"; do
        echo "$i: ${interfaces[$i]}"
    done

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

    # 确保用户输入有效
    if [ -z "${interfaces[$iface_index]}" ]; then
        echo "无效的选择"
        exit 1
    fi
    selected_interfaces=(${interfaces[$iface_index]})
    
elif [ "$operation_mode" = "2" ]; then
    # 所有网卡模式
    echo "将配置所有网卡:"
    for iface in "${interfaces[@]}"; do
        echo "  $iface"
    done
    echo
    echo -n "确认配置所有网卡? (y/n): "
    read confirm_all_interfaces
    
    if [ "$confirm_all_interfaces" != "y" ]; then
        echo "操作已取消"
        exit 0
    fi
    
    selected_interfaces=("${interfaces[@]}")
else
    echo "无效的选择"
    exit 1
fi

# 处理选中的网卡
for iface in "${selected_interfaces[@]}"; do
    echo
    echo "=========================================="
    echo "正在处理网卡: $iface"
    echo "=========================================="
    
    # 跳过回环接口
    if [ "$iface" = "lo" ]; then
        echo "跳过回环接口: $iface"
        continue
    fi
    
    # 检查网卡是否存在队列目录
    if [ ! -d "/sys/class/net/$iface/queues" ]; then
        echo "跳过无队列目录的接口: $iface"
        continue
    fi
    
    # 获取队列
    echo "获取 $iface 的队列..."
    tx_queues=( $(ls /sys/class/net/$iface/queues/ 2>/dev/null | grep "^tx-" | sort -V || true) )
    rx_queues=( $(ls /sys/class/net/$iface/queues/ 2>/dev/null | grep "^rx-" | sort -V || true) )

    echo "$iface 共有 ${#rx_queues[@]} 个 RX 队列，${#tx_queues[@]} 个 TX 队列"
    
    # 如果没有队列，跳过
    if [ ${#rx_queues[@]} -eq 0 ] && [ ${#tx_queues[@]} -eq 0 ]; then
        echo "跳过无队列的接口: $iface"
        continue
    fi
    
    echo

    # 检查 XPS 支持情况 - 只检查实际存在的TX队列
    declare -a xps_supported_queues=()
    xps_supported_count=0
    
    for queue in "${tx_queues[@]}"; do
        xps_file="/sys/class/net/$iface/queues/$queue/xps_cpus"
        # 检查文件存在、可读、可写
        if [ -f "$xps_file" ] && [ -r "$xps_file" ] && [ -w "$xps_file" ]; then
            # 尝试读取内容确认文件有效
            if cat "$xps_file" >/dev/null 2>&1; then
                xps_supported_queues+=("$queue")
                ((xps_supported_count++))
            fi
        fi
    done

    # 显示当前RPS值
    if [ ${#rx_queues[@]} -gt 0 ]; then
        echo "当前 RPS CPU 绑定值:"
        for queue in "${rx_queues[@]}"; do
            rps_file="/sys/class/net/$iface/queues/$queue/rps_cpus"
            if [ -f "$rps_file" ]; then
                current_rps=$(cat $rps_file 2>/dev/null || echo "无法读取")
                echo "  $queue: $current_rps"
            fi
        done
    fi

    # 显示当前XPS值（仅支持的队列）
    if [ ${#tx_queues[@]} -gt 0 ]; then
        echo
        echo "当前 XPS CPU 绑定值:"
        if [ $xps_supported_count -gt 0 ]; then
            for queue in "${xps_supported_queues[@]}"; do
                xps_file="/sys/class/net/$iface/queues/$queue/xps_cpus"
                current_xps=$(cat $xps_file 2>/dev/null || echo "无法读取")
                echo "  $queue: $current_xps"
            done
            if [ $xps_supported_count -lt ${#tx_queues[@]} ]; then
                echo "  注意: ${#tx_queues[@]} 个TX队列中有 $((${#tx_queues[@]} - xps_supported_count)) 个不支持XPS"
            fi
        else
            echo "  此网卡不支持XPS配置"
        fi
    fi

    echo
    if [ "$operation_mode" = "1" ]; then
        config_msg="确认修改 $iface 的所有队列的 RPS"
        if [ $xps_supported_count -gt 0 ]; then
            config_msg="$config_msg 和 XPS"
        fi
        config_msg="$config_msg? (y/n): "
        echo -n "$config_msg"
        read confirm_single
        if [ "$confirm_single" != "y" ]; then
            echo "跳过网卡 $iface"
            continue
        fi
    else
        echo "自动配置网卡 $iface..."
    fi

    # 修改RPS设置
    rps_success=0
    rps_total=0
    if [ ${#rx_queues[@]} -gt 0 ]; then
        echo
        echo "开始修改 RPS 设置..."
        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 2>/dev/null || echo "00000000")
                new_rps=$(echo "$format" | sed 's/[0-9a-fA-F]/f/g')
                echo "  $queue: $format -> $new_rps"
                
                if echo "$new_rps" | sudo tee $rps_file > /dev/null 2>&1; then
                    ((rps_success++))
                else
                    echo "    错误: 设置 $queue RPS 失败"
                fi
                ((rps_total++))
            fi
        done
    fi

    # 修改XPS设置（仅处理支持的队列）
    xps_success=0
    xps_total=0
    if [ $xps_supported_count -gt 0 ]; then
        echo
        echo "开始修改 XPS 设置..."
        for queue in "${xps_supported_queues[@]}"; do
            xps_file="/sys/class/net/$iface/queues/$queue/xps_cpus"
            format=$(cat $xps_file 2>/dev/null || echo "00000000")
            new_xps=$(echo "$format" | sed 's/[0-9a-fA-F]/f/g')
            echo "  $queue: $format -> $new_xps"
            
            if echo "$new_xps" | sudo tee $xps_file > /dev/null 2>&1; then
                ((xps_success++))
            else
                echo "    错误: 设置 $queue XPS 失败"
            fi
            ((xps_total++))
        done
    fi

    echo
    echo "验证修改结果..."
    echo
    
    # 验证RPS设置
    rps_verify_success=0
    if [ ${#rx_queues[@]} -gt 0 ]; then
        echo "验证 RPS 设置结果:"
        for queue in "${rx_queues[@]}"; do
            rps_file="/sys/class/net/$iface/queues/$queue/rps_cpus"
            if [ -f "$rps_file" ]; then
                current_rps=$(cat $rps_file 2>/dev/null)
                if [ -n "$current_rps" ]; then
                    expected_rps=$(echo "$current_rps" | sed 's/[0-9a-fA-F]/f/g')
                    if [ "$current_rps" = "$expected_rps" ]; then
                        echo "  $queue: $current_rps ✓"
                        ((rps_verify_success++))
                    else
                        echo "  $queue: $current_rps ✗ (期望: $expected_rps)"
                    fi
                else
                    echo "  $queue: 读取失败 ✗"
                fi
            fi
        done
    fi

    # 验证XPS设置（仅验证支持的队列）
    xps_verify_success=0
    if [ $xps_supported_count -gt 0 ]; then
        echo
        echo "验证 XPS 设置结果:"
        for queue in "${xps_supported_queues[@]}"; do
            xps_file="/sys/class/net/$iface/queues/$queue/xps_cpus"
            current_xps=$(cat $xps_file 2>/dev/null)
            if [ -n "$current_xps" ]; then
                expected_xps=$(echo "$current_xps" | sed 's/[0-9a-fA-F]/f/g')
                if [ "$current_xps" = "$expected_xps" ]; then
                    echo "  $queue: $current_xps ✓"
                    ((xps_verify_success++))
                else
                    echo "  $queue: $current_xps ✗ (期望: $expected_xps)"
                fi
            else
                echo "  $queue: 读取失败 ✗"
            fi
        done
    fi

    echo
    echo "修改汇总 ($iface):"
    if [ ${#rx_queues[@]} -gt 0 ]; then
        echo "  RPS: ${rps_success:-0}/${rps_total:-0} 个队列设置成功, ${rps_verify_success:-0}/${rps_total:-0} 个队列验证通过"
    fi
    if [ $xps_supported_count -gt 0 ]; then
        echo "  XPS: ${xps_success:-0}/${xps_total:-0} 个队列设置成功, ${xps_verify_success:-0}/${xps_total:-0} 个队列验证通过"
    elif [ ${#tx_queues[@]} -gt 0 ]; then
        echo "  XPS: 不支持（跳过）"
    fi
    
    # 计算总体成功率
    total_verify=$((${rps_verify_success:-0} + ${xps_verify_success:-0}))
    total_expected=$((${rps_total:-0} + ${xps_total:-0}))
    
    if [ $total_verify -eq $total_expected ] && [ $total_expected -gt 0 ]; then
        echo "  状态: 所有支持的设置均成功应用 ✓"
    elif [ $total_expected -eq 0 ]; then
        echo "  状态: 无可配置的队列"
    else
        echo "  状态: 部分设置可能未成功应用，请检查权限或系统状态 ✗"
    fi
    
    # 清理数组，避免下次循环时残留数据
    unset xps_supported_queues
done

echo
echo "配置完成!"