#!/bin/bash

set_an() {
    local AssetNum=$1
    rm -rf /tmp/fwupdate > /dev/null 2>&1
    mkdir -p /tmp/fwupdate > /dev/null 2>&1
    wget http://softlib.service.ucloud.cn/usa/fw/$Manufacture/SETBIOS/setbios.tgz -O /tmp/fwupdate/setbios.tgz > /dev/null 2>&1
    cd /tmp/fwupdate
    tar zxf setbios.tgz > /dev/null 2>&1
    sh update_an.sh $AssetNum > /dev/null 2>&1
}

_install() {
    if [[ $VMFLAG = 1 ]];then
        return 0
    fi
    if [[ $ENVFLAG = 'offline' ]];then
        return 0
    fi
    
    de_an=`dmidecode -s chassis-asset-tag |grep -v ^#|sed 's/ //g'`
    if [[ "${ManufactureType}" =~ "I620-G20" ]] && [[ $isco != "CO" && $de_an != $AN ]];then
        set_an $AN
        status=$?
        cd $BASEDIR/modules/
        [[ $status == 0 ]] || PRINT_INFO "[INFO]尝试修改AN失败1 请联系硬件运维手动修改AN为: $AN"
        # return $status
    fi
    if [[ $de_an != $AN ]];then
        mkdir -p /tmp/fw_update/Update_fru/
        wget -qN http://softlib.service.ucloud.cn/usa/fw/fru/Update_fru.tgz -O /tmp/fw_update/Update_fru.tgz && tar xf /tmp/fw_update/Update_fru.tgz -C /tmp/fw_update/
        pushd /tmp/fw_update/Update_fru/ || return 1
        bash -x ucloud-update-fru.sh &> ucloud-update-fru.log
        status=$?
        popd || return 1
        [[ $status == 0 ]] || PRINT_INFO "[INFO]尝试修改AN失败2 请联系硬件运维手动修改AN为: $AN"
        # return $status
    fi
}

_check() {
	_check="PASS"

    if [[ $VMFLAG = 1 ]];then
        return 0
    fi
    if [[ $ENVFLAG = 'offline' ]];then
        return 0
    fi

    de_sn=`dmidecode -s system-serial-number |grep -v ^#|sed 's/ //g'`
    de_an=`dmidecode -s chassis-asset-tag |grep -v ^#|sed 's/ //g'`
    [[ ! $de_an =~ "UCSV" ]] && de_an=`dmidecode -s baseboard-asset-tag |grep -v ^#|sed 's/ //g'`
    #[[ -z $de_an || $de_an =~ "O.E.M" || $de_an =~ BADINDEX ]] && de_an=`dmidecode -s baseboard-asset-tag |grep -v ^#|sed 's/ //g'`
    [[ $de_sn =~ BADINDEX ]]  && de_sn=''
    [[ $de_an =~ BADINDEX ]]  && de_an=''
    ipmi_sn=`ipmitool fru list 0|grep 'Product Serial'| awk '{print $4}'|sed 's/ //g'`
    ipmi_an=`ipmitool fru list 0|grep "Product Asset Tag"|awk -F ": " '{print $2}'|sed 's/ //g'`
    [[ $ipmi_sn =~ BADINDEX ]]  && local_sn=''
    [[ $ipmi_an =~ BADINDEX ]]  && local_an=''

    if [[ $de_sn != $SN ]];then
        _check="FAIL"
        PRINT_ERR "[ERROR] Dmidecode -s system-serial-number SN: $de_sn, Not Match CMDB SN: $SN, 请联系硬件运维手动修改SN为: $SN"
    fi
    if [[ $ipmi_sn != $SN ]];then
        _check="FAIL"
        PRINT_ERR "[ERROR] IPMI fru Product Serial SN: $ipmi_sn, Not Match CMDB SN: $SN, 请联系硬件运维手动修改SN为: $SN"
    fi
    if [[ $isco != "CO" && $de_an != $AN ]];then
        _check="FAIL"
        PRINT_ERR "[ERROR] Dmidecode -s chassis-asset-tag AN: $de_an, Not Match CMDB AN: $AN, 请联系硬件运维手动修改AN为: $AN"
    fi
    if [[ $isco != "CO" && $ipmi_an != $AN ]];then
        _check="FAIL"
        PRINT_ERR "[ERROR] IPMI fru Product Asset Tag AN: $ipmi_an, Not Match CMDB AN: $AN, 请联系硬件运维手动修改AN为: $AN"
    fi
}
