#!/usr/bin/env bash

update_nic() {
    action=$1
    exit_code=0
    
    if [[ $(lspci|grep 'Ethernet'|grep -ci "mellanox") -eq 0 ]];then
        return 0
    fi
    
    KernelGeneration=''
    if [[ $(uname -r) =~ '4.14.0' ]];then
        KernelGeneration='4.14'
    elif [[ $(uname -r) =~ '5.10.0' ]];then
        KernelGeneration='5.10'
    elif [[ $(uname -r) =~ '4.1.0' ]];then
        KernelGeneration='4.1'
    fi

    if [[ -z $KernelGeneration ]];then
        PRINT_ERR "[ERROR] can not get KernelGeneration"
        return 1
    fi

    mlx_pci_list=$(/bin/mlxup --query |grep "PCI Device Name"|awk '{print $NF}')
    for mlx_pci in ${mlx_pci_list[@]}
    do
        query_info=$(/bin/mlxup -d "$mlx_pci" --query)
        part_number=$(echo "$query_info" |grep "Part Number" |awk '{print $NF}')
        fw=$(echo "$query_info" |grep "FW" |grep -v "Running" | awk '{print $2}')
        fw_path="NIC/Mellanox/${part_number}/${KernelGeneration}"
        fw_version=$(/usr/bin/python $BASEDIR/utils/GetApolloConf.py "NIC" "$fw_path" fw)
        if [[ -z $fw_version ]];then
            PRINT_ERR "[ERROR] -> NIC $fw_path <- Not Exist In UCONF, Please Check UCONF"
            exit_code=2
        fi
        if [[ $fw_version =~ $fw ]];then
            PRINT_INFO "[INFO] Firmware $fw_path: '$fw' in '$fw_version'"
        else
            PRINT_ERR "[INFO] Firmware $fw_path: '$fw' not in '$fw_version'"
            exit_code=2
            if [[ $action = 'install' ]];then
                run_fw_update $fw_path $mlx_pci
                if [[ $? -ne 0 ]];then
                    exit_code=1
                fi
            fi
        fi
    done
    
    return $exit_code
}

run_fw_update () {
    # 固件目录名称和文件名称不带空格，替换成下划线
    local path=$1
    path=$(echo $path|tr ' ' '_')
    local arg=$2 # only for Mellanox,need pci address
    mkdir -p /tmp/fw_update/$path
    wget -q -N http://softlib.service.ucloud.cn/usa/firmware/$path/fw_update.tgz -P /tmp/fw_update/$path/
    if [[ $? -ne 0 ]];then
        PRINT_INFO "[INFO] Wget $path failed, Not Support AutoUpdate"
        return 0
    fi

    tar xf /tmp/fw_update/$path/fw_update.tgz -C /tmp/fw_update/$path
    cd /tmp/fw_update/$path && bash update.sh $arg > update.log 2>&1
    cd $BASEDIR/modules
    if [[ $? -eq 0 ]];then
        PRINT_INFO "[INFO] Update $path $arg Success"
        return 0
    else
        PRINT_ERR "[ERROR] Update $path $arg Failed"
        return 1
    fi
}

_install() {
    update_nic install
    if [[ $? -eq 1 ]];then
        return 1
    fi
}

_check() {
    _check="PASS"
    update_nic check
    if [[ $? -eq 2 ]];then
        _check="FAIL"
        return 1
    fi
}
