#!/bin/bash

# Description: H3C R4700 G3 BMC Fw Update
# 2020-04-29: 拆分BMC/BIOS/RAID升级包（allin.han）
# 2021/08/18: 厂商机型信息修正

currentDir=`pwd`
resultLog="`pwd`/result.log"

source "${currentDir}/bmc.conf"

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
}

#Check the dedicated nic's channel ID is 1, if not, change it.
function checekChannelIDAndUpdate() {
	isChannelOne=`ipmitool  raw 0x36 0x05 0xA2 0x63 0x00 0x0C | awk '{print $4}'`
	if [ "${isChannelOne}" == "00" ]; then
		ipmitool raw 0x36 0x09 0xa2 0x63 0x00 0x2d 0x01
	fi
}

#Update Board manufacturer and product manufacturer to H3C
#Update product name to simple name to R4700 G3.
function updateFru() {
	bash ${currentDir}/UpdateFru.sh -K BM "H3C"
        bash ${currentDir}/UpdateFru.sh -K PM "H3C"
	productName=`ipmitool fru print 0 | grep "Product Name" | cut -d':' -f 2| sed 's/^ //'`
	if [ "`echo ${productName} | grep 'R4700 G3'`" != "" ]; then
		bash ${currentDir}/UpdateFru.sh -K PN "R4700 G3"
	elif [ "`echo ${productName} | grep 'R4300 G3'`" != "" ]; then
		bash ${currentDir}/UpdateFru.sh -K PN "R4300 G3"
	elif [ "`echo ${productName} | grep 'R4900 G3'`" != "" ]; then
		bash ${currentDir}/UpdateFru.sh -K PN "R4900 G3"
	fi
}

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
	sleep 180s
	bash curl.sh -I ${ipmi_ip} -U root -P ${ipmi_password} -T HDM -M main -F ${bmcFile} -R 2 -K 0 -V 1
}

checekChannelIDAndUpdate

sleep 10s

updateFru

sleep 10s

getIpmiIPAndPasswd

bmcVersionCheckAndUpdate

ipmiStatus

checekChannelIDAndUpdate
