# ==============================
# NIC tuning (UP + IRQ + RPS/XPS + Offload + ring buffer)
# ==============================
echo "[INFO] NIC tuning bắt đầu..."

# Lấy danh sách NIC khả dụng (bỏ lo, docker, virbr, ...)
NIC_LIST=$(ls /sys/class/net | grep -v -E 'lo|virbr|docker')

if [ -z "$NIC_LIST" ]; then
    echo "[WARN] Không có NIC nào khả dụng!"
else
    for nic in $NIC_LIST; do
        echo "[INFO] Xử lý NIC: $nic"

        # Bật NIC nếu chưa UP
        state=$(cat /sys/class/net/$nic/operstate)
        if [ "$state" != "up" ]; then
            ip link set $nic up
            echo "[INFO] NIC $nic chưa UP, đã bật"
        fi

        # Set ring buffer (rx/tx 4096)
        if command -v ethtool >/dev/null 2>&1; then
            ethtool -G $nic rx 4096 tx 4096 || true
            echo "[INFO] NIC $nic đã set ring buffer RX/TX 4096"
        fi

        # Set RPS/XPS mask (phân bổ cho tất cả CPU core)
        RPS_MASK=$(printf "%x" $(( (1 << $CPU_CORES) - 1 )))

        # RPS
        for q in /sys/class/net/$nic/queues/rx-*; do
            echo $RPS_MASK > $q/rps_cpus
        done

        # XPS
        for q in /sys/class/net/$nic/queues/tx-*; do
            echo $RPS_MASK > $q/xps_cpus
        done

        # IRQ affinity
        IRQs=$(grep $nic /proc/interrupts | awk '{print $1}' | sed 's/://')
        i=0
        for irq in $IRQs; do
            core=$(( i % CPU_CORES ))
            MASK=$((1 << core))
            printf "%x" $MASK > /proc/irq/$irq/smp_affinity
            ((i++))
        done

        # Offload tuning (tắt delay, giữ checksum)
        if command -v ethtool >/dev/null 2>&1; then
            ethtool -K $nic gro off gso off tso off lro off ufo off rx on tx on || true
            echo "[INFO] NIC $nic đã set offload (gro/gso/tso/lro/ufo off, rx/tx checksum on)"
        fi

        echo "[INFO] NIC $nic tối ưu xong"
    done
fi

echo "[DONE] Tối ưu network TCP/UDP + NIC UP + IRQ/RPS/XPS + Offload + Ring Buffer hoàn tất!"

