#!/bin/bash

# Get the list of network interfaces
interfaces=$(ls /sys/class/net/)

# Loop through each interface
for interface in $interfaces; do
    # Get the maximum RX and TX ring buffer values
    output=$(ethtool -g $interface 2>/dev/null)
    
    # Print the raw output for debugging
    echo "Output for $interface:"
    echo "$output"
    
    # Check if ethtool was able to retrieve the info 
    if [[ $? -eq 0 ]]; then
        # Extract max RX and TX values
        max_rx=$(echo "$output" | grep -A 5 "Pre-set maximums:" | grep "RX:" | awk '{print $2}')
        max_tx=$(echo "$output" | grep -A 5 "Pre-set maximums:" | grep "TX:" | awk '{print $2}')

        # Extract current RX and TX values
        current_rx=$(echo "$output" | grep -A 5 "Current hardware settings:" | grep "RX:" | awk '{print $2}')
        current_tx=$(echo "$output" | grep -A 5 "Current hardware settings:" | grep "TX:" | awk '{print $2}')

        # Check if we found valid numeric values for RX and TX
        if [[ "$max_rx" =~ ^[0-9]+$ ]] && [[ "$max_tx" =~ ^[0-9]+$ ]] && [[ "$current_rx" =~ ^[0-9]+$ ]] && [[ "$current_tx" =~ ^[0-9]+$ ]]; then
            echo "Max RX: $max_rx, Max TX: $max_tx"
            echo "Current RX: $current_rx, Current TX: $current_tx"
            
            # Only change the settings if the current value is less than the max value
            if [[ "$current_rx" -lt "$max_rx" ]] || [[ "$current_tx" -lt "$max_tx" ]]; then
                echo "Setting RX and TX for $interface to max values: RX=$max_rx TX=$max_tx"
                sudo ethtool -G $interface rx $max_rx tx $max_tx
            else
                echo "No need to change settings for $interface. RX and TX are already at max values."
            fi
        else
            echo "Invalid or unsupported RX/TX values for $interface."
        fi
    else
        echo "Cannot get device ring settings for $interface: Operation not supported"
    fi
done


