#!/bin/bash
rpm -qa |grep jq
if [ $? = 0 ];then
	echo "The package has been installed"
else
	yum install jq -y
fi
ipmi_ip=$(ipmitool lan print |grep "IP Address  " |awk -F ": " '{print$2}')
SN=$(dmidecode -s system-serial-number |grep -v ^#  | sed s/[[:space:]]//g)
passwd=$(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 $passwd  ]] || exit 1
netmask=$(ipmitool lan print |grep "Subnet Mask" |awk -F ": " '{print$2}')
gateway=$(ipmitool lan print |grep "Default Gateway IP" |awk -F ": " '{print$2}')

function Enable_VD() {
	echo "====== Enable virtual device ======"
	ipmitool raw 0x32 0xaa 0x00 
}

function BMCUpdating() {
	uname -a |grep el6
	if [ "$?" = 0 ];then
		service ipmi restart
	else
		systemctl restart ipmi.service
	fi
	echo "*** BMC updating ***"
	ima_file=$(ls *.ima)
	yes|./Yafuflash -cd $ima_file -preserve-config
}

function UserSetting() {
	echo "*** Config User related settings ***"
	#//Create new user named "root"
	ipmitool user set name 2 root
	#//Enabled the new user
	ipmitool user enable 2
	#//Set new password to root
	ipmitool user set password 2 $passwd
	#//Set the administrator priv to root
	ipmitool user priv 2 4 1
	#//Set the highest access priv to root
	ipmitool channel setaccess 1 2 callin=on link=on ipmi=on
}

function IPMISetting() {
	echo "*** Config IPMI related settings ***"
	if [ $(ipmitool lan print |grep "IP Address Source" |awk -F ": " '{print$2}' |awk -F " " '{print$1}') = "Static" ];then
		echo "IPMI has been set completely"
	elif [ $(ipmitool lan print |grep "Default Gateway IP" |awk -F ": " '{print$2}') = "0.0.0.0" ];then
	        ipmitool lan set 1 ipsrc static
        	ipmitool lan set 1 ipaddr $ipmi_ip
        	ipmitool lan set 1 netmask $netmask
        	ipmitool lan set 1 defgw ipaddr $gateway
        	#ipmitool user set password 2 $passwd
	else
		ipmitool lan set 1 ipsrc static
		ipmitool lan set 1 ipaddr $ipmi_ip
		#ipmitool user set password 2 $passwd
	fi
}
Enable_VD
BMCUpdating
#UserSetting
#IPMISetting
