#!/bin/bash

################################################################################
## Copyright:   HUAWEI Tech. Co., Ltd.
## Filename:    modify_nic_max_buffer.sh
## Description: rollback the nic buffer size modified by FusionInsight
################################################################################
declare -r CURRENT_PATH=$(cd `dirname $0`; pwd)
declare -r LOG_PATH=$CURRENT_PATH/../../../
declare -r LOG_FILE="${LOG_PATH}"/cloud/util/log/log.sh

# ---------------------------------------------------------------------------- #
#                                   脚本导入                                    #
# ---------------------------------------------------------------------------- #
. "${LOG_FILE}" || { echo "[${g_scriptName}:${LINENO}] ERROR: Failed to load ${LOG_FILE}."; exit 1;}


######################################################################
#   DESCRIPTION: rollback the nic buffer size modified by FusionInsight
######################################################################
function ethtool_config()
{
    local bak_rx_buffer=256
    local bak_tx_buffer=256
    local blacklist=$1
    OLD_IFS="$IFS" #保存旧的分隔符
    IFS=";;"
    array=($blacklist)
    IFS="$OLD_IFS" # 将IFS恢复成原来的
    for i in "${!array[@]}"; do
        DEV=${array[i]}
        ethtool -g $DEV > /dev/null 2>&1
        if [ $? -ne 0 ]; then
            showLog_info "${LINENO}" "Skip to set the $DEV,because it is not the physical network card."
            continue
        fi

        # 当前RX
        CURRX=$(ethtool -g $DEV | grep RX: | sed -n 2p | awk '{print $NF}')

        if [ $CURRX -gt $bak_rx_buffer ]; then
            ethtool -G $DEV rx $bak_rx_buffer
            if [ $? -ne 0 ]; then
                showLog_error "${LINENO}" "Setting the rx of the $DEV fails."
                return 0
            fi
        fi


        # 当前TX
        CURTX=$(ethtool -g $DEV | grep TX: | sed -n 2p | awk '{print $NF}')

        if [ $CURTX -gt $bak_tx_buffer ]; then
            ethtool -G $DEV tx $bak_tx_buffer
            if [ $? -ne 0 ]; then
                showLog_error "${LINENO}" "Setting the rx of the $DEV fails."
                return 0
            fi
        fi
    done

    return 0
}

######################################################################
#   DESCRIPTION: 网络缓存调优主执行函数
######################################################################
function main()
{
    dmidecode -t 1 | grep 'Manufacturer' | grep 'VMware\|Xen\|OpenStack\|QEMU' > /dev/null 2>&1
    if [ $? -eq 0 ];
    then
        showLog_info "${LINENO}" "No need to configure this parameter for VMs."
        return 0
    fi

    showLog_info "${LINENO}" "Start to modify the nic buffer."
    ethtool_config $*
    if [ $? -ne 0 ]; then
        showLog_error "${LINENO}" "Exception occurs when Setting the ethtool options."
        return 1
    fi

    showLog_info "${LINENO}" "Success to modify the nic buffer."
    return 0
}

main $*
# 部分网口无法释放内存故所有结果返回成功
exit 0