#!/bin/bash

### Get Product Info with underline
Product=$(echo $ManufactureType|sed "s/^${Manufacture} //g")

setbios() {
    (
        # ipmi password
    local json1 IPMI_pw 
    json1=$(curl -s -H "Content-Type:application/json" -X POST --data  '{"data":  ["'"$IPMI"'"],"type": "IPMI"}' http://udcm.ucloudadmin.com/api/ipmi/v1/getpwd/)
    IPMI_pw=$(echo "$json1" | jq -r .[].IPMIPassword)
    if [[ -z "$IPMI_pw" ]];then
        IPMI_pw="ucloud.cn"
    fi

    mkdir -p /tmp/fw_update/${Manufacture}/SETBIOS
    cd /tmp/fw_update/${Manufacture}/SETBIOS || return 2
    wget http://softlib.service.ucloud.cn/usa/firmware/SERVER/$Manufacture/SETBIOS/setbios.tgz -O /tmp/fw_update/${Manufacture}/SETBIOS/setbios.tgz > /dev/null 2>&1
    [[ $? != 0 ]] && { PRINT_ERR "[ERROR] Failed wget --> usa/firmware/SERVER/$Manufacture/SETBIOS/setbios.tgz <-- 下载出错"; return 1; }
    [[ -s setbios.tgz ]] && tar xf setbios.tgz || return 2
    if [[ $1 == "install" ]];then
        bash bios_setting.sh "${ManufactureType}" "install" "$IPMI_pw" &>> /tmp/fw_update/log-bios_setting.log
        return $?
    elif [[ $1 == "check" ]];then
        bash bios_setting.sh "${ManufactureType}" "check" &>> /tmp/fw_update/log-bios_setting.log
        return $?
    else
        return 3
    fi
    )
}

check_bios () {
    local BIOS_VERSION BIOS_RELEASE_DATE L_BIOS_VER
    if [[ $Manufacture == "HP" ]];then
        BIOS_VERSION=`dmidecode -t 0 |grep "Version"|awk -F ": " '{print $2}'`
        BIOS_RELEASE_DATE=`dmidecode -t0|grep "Release Date"|awk -F ": " '{print $2}'`
        L_BIOS_VER="$BIOS_VERSION $BIOS_RELEASE_DATE"
    else
        L_BIOS_VER=`dmidecode -s bios-version|sed '/^#/d'`
    fi

    R_BIOS_VER=`/usr/bin/python $BASEDIR/utils/GetApolloConf.py "BIOS" "${Manufacture}.${Product}.BIOS" fw`
    [[ -z $R_BIOS_VER ]] && PRINT_ERR "[ERROR] BIOS FW --> BIOS ${Manufacture}.${Product}.BIOS <-- Not Exist In UCONF, Please Check UCONF"
    [[ "$R_BIOS_VER" =~ "$L_BIOS_VER" ]] || return 1
}

_install() {
    check_bios
    [[ $? -eq 1 ]] && return 0

    setbios "install"
    local set_bios_status=$?
    if [[ $set_bios_status == 0 ]];then
        PRINT_INFO "[INFO] BIOS Config Import Success"
    else
        PRINT_ERR "[ERROR] BIOS Config Import Failed"
    fi
    return $set_bios_status
}

_check() {
    _check="PASS"

    if [[ $ARCH != 'x86_64' ]];then
        return 0
    fi
    # check cpu monitor flag
    if [[ $(cat /proc/cpuinfo | grep -ci monitor) -eq 0 ]]; then
        _check="FAIL"
        PRINT_ERR "[ERROR] CPU Monitor Flag Disabled"
        return 1
    fi
}
