#!/bin/bash
currentDir=`pwd`
resultLog="`pwd`/result.log"

source "${currentDir}/bmc.conf"



function getIpmiIPAndPasswd() {
        ipmi_ip=`ipmitool  lan print 1 | grep "IP Address  "| awk '{print $NF}'`
        if [ "${ipmi_ip}" != "0.0.0.0" ]; then
                SN=$(dmidecode -s system-serial-number |grep -v ^#  | sed s/[[:space:]]//g)
                ipmi_password=$(curl -s -H "Content-Type:application/json" -X POST --data  '{"data":  ["'${SN}'"],"type": "SN"}' http://udcm.ucloudadmin.com/api/ipmi/v1/getpwd/ | jq -r '.[]|.IPMIPassword')
                [[ -n $ipmi_password ]] || exit 1
        fi
        if [ "${ipmi_password}" == "" ]; then
                ipmi_password="ucloud.cn"
        fi
}

function bmcVersionCheckAndUpdate() {
        prefix=`ipmitool mc info | grep "Firmware Revision"|awk '{print $NF}'`
        suffix=`ipmitool mc info | grep -A 1 "Aux Firmware Rev Info"| tail -n 1 |awk '{print $1}'`
        bmcSuffix=`printf %d ${suffix}`
        bmcVersion="${prefix}.${bmcSuffix}"
        bash curl.sh -I ${ipmi_ip} -U root -P ${ipmi_password} -T HDM -M back -F ${bmcFile} -R 2 -K 0 -V 1
	bash curl.sh -I ${ipmi_ip} -U root -P ${ipmi_password} -F ${bmcFile} -R 1 -K 0 -B 1
}

function ipmiStatus() {
        ipmitool mc reset cold
        sleep 180s
        testString=`ipmitool fru print 0`

        if [ "${testString}" = "" ]; then
                ipmiStatus=1
                echo "ipmi not work" >> ${resultLog}
                exit 1
        fi
}

getIpmiIPAndPasswd
ipmitool -I lanplus -H ${ipmi_ip}  -U root -P ${ipmi_password} raw 0x36 0x02 0x20 0x14 0x00 0x80 0xcd 0x01 0x01 0x01
bmcVersionCheckAndUpdate
sleep 30s
ipmiStatus


