#!/bin/sh

FUNNAME="curl.sh"

# default var value
IP=""                                              # -I, HDM IP
USER="root"                                        # -U, user name
PWD="root"                                         # -P
FWTYPE="HDM"                                       # -T
FWNAME=""                                          # -F
REBOOT=2                                           # -R, 0: reboot automatically after FW updated successfully, 2: manually
MAINBACK=""                                        # -M, back: flash back_up HDM, main: flash main HDM
KEEPCONF=0                                         # -K, 0: keep, 1: not keep
VISIBLE=0                                          # -V, 0: no visible, ~0: visible   #added 2018-09-18, Des: show the progress of post file and flash FW or not

http="HTTP/1.1"
trytime=1
maxtime=5
intervaltime_max=30
intervaltime_min=5
SN=""                      # chassis serial number, added 2018-08-15
hdm_target_fw=""           # Added by c14146, 2018-08-21, Des: upgrade FW and login Web is or not OK
token=""                   # Added by c14146, 2018-08-21, Des: upgrade FW and login Web is or not OK
noreboot=2                 # Added by c14146, 2018-09-29, Des: HDM 1.00.26P01 not support reboot automatically
IsUpdateNext=false         # Added by c14146, 2018-10-29, Des: update BIOS after OS power down

# Usage
function Usage()
{
    echo -e "Usage:"
    echo -e "$1\t\tUpdate HDM or BIOS FW"
    echo -e "Option:"
    echo -e "\t <-I>: HDM IP"
    echo -e "\t <-U>: HDM UserName"
    echo -e "\t <-P>: HDM UserPassword"
    echo -e "\t <-T>: choose HDM or BIOS to update"
    echo -e "\t <-F>: firmware name"
    echo -e "\t <-R>: reboot automatically or manually"
    echo -e "\t <-M>: flash back_up or main flash"
    echo -e "\t <-K>: keep configuration"
    echo -e "\t <-V>: show the progress of post file and flash FW"   #added 2018-09-18, Des: show the progress of post file and flash FW or not
}

# IN arg
while getopts "I:U:P:T:F:R:M:K:V:" arg
do
    case $arg in
        I)
            IP="$OPTARG"
            ;;
        U)
            USER="$OPTARG"
            ;;
        P)
            PWD="$OPTARG"
            ;;
        T)
            FWTYPE="$OPTARG"
            ;;
        F)
            FWNAME="fwimage=@$OPTARG"
            ;;
        R)
            REBOOT="$OPTARG"
            ;;
        M)
            MAINBACK="$OPTARG"
            ;;
        K)
            KEEPCONF="$OPTARG"
            ;;
        V)
            VISIBLE="$OPTARG"
            ;;
        ?)
            echo "Unknow argment"
            Usage $FUNNAME
            exit 1
            ;;
    esac
done

# log path
mkdir -p ./log/$IP/$FWTYPE/$MAINBACK
log_path=./log/$IP/$FWTYPE/$MAINBACK

log_status=$log_path/status.txt
tmp_cmd_reply=$log_path/tmp_cmd_rep.txt
cookies=$log_path/cookies

# Check Input parameter
if [[ "$IP" == "" ]]; then
    echo "No UUT IP is given!!!" >> $log_status
    Usage $FUNNAME
    exit 1
fi
if [[ "$FWNAME" == "fwimage=@" ]]; then
    echo "No firmware file is given!!!" >> $log_status
    Usage $FUNNAME
    exit 1
fi
HDMFW=`echo $FWNAME |grep "HDM"`
BIOSFW=`echo $FWNAME |grep "BIOS"`
if [[ "$FWTYPE" == "HDM" ]] && [[ "$HDMFW" == "" ]]; then
    echo "HDM firmware file checked failed!!!" >> $log_status
    exit 1
fi
if [[ "$FWTYPE" == "BIOS" ]] && [[ "$BIOSFW" == "" ]]; then
    echo "BIOS firmware file checked failed!!!" >> $log_status
    exit 1
fi

PWD=`echo $PWD| sed 's/%/%25/g'`   # change some special character, added 2018-08-21
PWD=`echo $PWD| sed 's/+/%2B/g'`
PWD=`echo $PWD| sed 's/\//%2F/g'`
PWD=`echo $PWD| sed 's/?/%3F/g'`
PWD=`echo $PWD| sed 's/#/%23/g'`
PWD=`echo $PWD| sed 's/&/%26/g'`
PWD=`echo $PWD| sed 's/=/%3D/g'`

######################################################### BEGIN: function define #########################################################

############################################################
# fun name: fun_check_cur_reply
# Des:      judge the meaning of cur reply
############################################################
fun_check_cur_reply()
{
    cat $tmp_cmd_reply >> $log_status
    header_ok=`cat $tmp_cmd_reply |grep "HTTP/.*\s*200\s*OK"`
    body=`cat $tmp_cmd_reply |grep "{.*}"`
    body_ok=`cat $tmp_cmd_reply |grep "\"cc\":\s*0"`
    # judge the meaning of the cur reply
    if [[ "$header_ok" == "" ]]; then   # establish session failed
        return 10
    fi

    if [[ "$body" == "" ]]; then
        return 0
    fi

    cc=`echo $body |grep -Po "\"cc\": [\d]+" |awk '{print$2}'`
    if [[ "$cc" == "" ]]; then
        return 10
    fi
    
    return $((cc))
}

############################################################
# fun name: fun_goto_first_step
# Des:      when find HDM state is abnormal, goto first step
#           totally try 3 times
############################################################
fun_goto_first_step()
{
    echo "goto first step..." >> $log_status
    for (( i = 0; i < $maxtime; i++ )); do
        echo > $tmp_cmd_reply
        echo -e "start: `date`" >> $log_status
        curl -c $cookies -b $cookies -H "X-CSRFToken:${token}" -X POST -d "" $IP/api/maintenance/firmware/first_step -i --connect-timeout 30 -s > $tmp_cmd_reply 2>>$log_status
        fun_check_cur_reply
        if (( $? == 0 )); then
            return 0
        fi
        echo "goto first step failed, after $intervaltime_min(s) later, try again!" >> $log_status
        sleep $intervaltime_min
    done
    echo -e "\ntried $maxtime times and failed to goto the first step!!!" >> $log_status
    return 1
}

############################################################
# fun name: fun_get_flash_step
# Des:      get the flash state of HDM
#           totally try 3 times
# input:    step value, like 2, 3
############################################################
fun_get_flash_step()
{
    echo -e "\nget the flash state..." >> $log_status
    for (( i = 0; i < $maxtime; i++ )); do
        echo > $tmp_cmd_reply
        echo -e "start: `date`" >> $log_status
        curl -c $cookies -b $cookies -H "X-CSRFToken:${token}" $IP/api/maintenance/firmware/step -i --connect-timeout 30 -s > $tmp_cmd_reply 2>>$log_status
        fun_check_cur_reply
        if (( $? == 0 )); then   #delete get step
            return 0
        fi
        echo -e "\nget the flash state failed, after $intervaltime_min(s) later, try again!" >> $log_status
        sleep $intervaltime_min
    done
    echo -e "\ntried $maxtime times and failed to get the flash state!!!" >> $log_status
    return 1
}

############################## BEGIN: Added by c14146, 2018-08-21, Des: upgrade FW and login Web is or not OK ##############################
fun_establish_session()
{
    # Establish session
    trytime=1
    echo -e "\n\nEstablish session..." >> $log_status
    while(( $trytime <= $maxtime ))
    do
        echo "try=$trytime" >> $log_status
        echo > $tmp_cmd_reply
        echo -e "start: `date`" >> $log_status
        curl -c $cookies -d "username=$USER&password=$PWD" $IP/api/session -i --connect-timeout 30 -S > $tmp_cmd_reply 2>>$log_status
        fun_check_cur_reply
        result=$?
        if (( $result == 0 )); then
            token=`grep -Po "(?<=CSRFToken\": \")[\d\w]+" $tmp_cmd_reply`
            echo "token=$token" >> $log_status
            echo "Establish session success!" >> $log_status
            return 0
        else
            if (( $trytime == $maxtime )); then
                echo -e "\nupdate $IP $FWTYPE FW failed, check network env, login info and HDM state is OK or not" >> $log_status
                return 1
            fi
            if (( $result == 10 )); then
                echo -e "\nthe network is obstructed, after $intervaltime_max(s) later, try again!!!" >> $log_status
                sleep $intervaltime_max
            else
                if (( $result == 1 )); then
                    echo -e "\nlogin failed, ensure USER and PWD is correct!!!" >> $log_status
                    return 1
                fi
                if (( $result == 2 )); then
                    echo -e "\nconnect AD/LDAP failed, ensure USER and PWD is correct!!!" >> $log_status
                    return 1
                fi
                if (( $result == 3 )); then
                    echo -e "\nthe number of sessions is too much, wait 30min and try again!!!" >> $log_status
                    return 1
                fi
                if (( $result == 4 )); then
                    echo -e "\nthe user is not allowed to login in the Web, ensure USER and PWD is correct!!!" >> $log_status
                    return 1
                fi
                if (( $result == 5 )); then
                    echo -e "\nFW is under upgrading, wait 5min and try again!!!" >> $log_status
                    return 1
                fi
                if (( $result == 6 )); then
                    echo -e "\nthe PWD has been overdue, ensure USER and PWD is correct!!!" >> $log_status
                    return 1
                fi
                echo -e "\nundefined cc value, after $intervaltime_min(s) later, try again!!!" >> $log_status
                sleep $intervaltime_min
            fi
            let trytime++
        fi
    done
}
############################## ENDL Added by c14146, 2018-08-21, Des: upgrade FW and login Web is or not OK ##############################

######################################################### END: function define #########################################################

############################################################
# fun name: fun_one_time_upgrade
# Des:      one primary flow to upgrade HDM or BIOS
# Output:   0: success, 1: failed
############################################################
fun_one_time_upgrade()
{
    IsUpdateNext=false         # Added by c14146, 2018-10-29, Des: update BIOS after OS power down

    echo -e "\n\n\n\n\n\n`date`" >> $log_status

    # Establish session
    fun_establish_session
    session_result=$?
    if (( $session_result != 0 )); then
        return 1
    fi
    sleep 2

    ############################## BEGIN: get chassis serial number by restful interface, added 2018-08-18 ##############################
    echo -e "\n\nget chassis serial number..." >> $log_status
    echo -e "start: `date`" >> $log_status
    baseboard_chassis=`curl -c $cookies -b $cookies -H "X-CSRFToken:${token}" $IP/api/fru -i --connect-timeout 30 -S 2>>$log_status |grep -Po '"device_name": "BaseBoard", "chassis": {.*?}'`
    echo -e "end: `date`" >> $log_status
    if [[ "$baseboard_chassis" == "" ]]; then
        echo "get null chassis serial number!!!" >> $log_status
        SN="NA"
    else
        SN=`echo $baseboard_chassis |grep -Po '"serial_number": "\w+"' |awk -F ':' '{print$2}' |sed 's/ //g' |sed 's/"//g'`
        if [[ "$SN" == "" ]]; then
            echo "get null chassis serial number!!!" >> $log_status
            SN="NA"
        else
            echo "the serial number(SN) of the server is: $SN" >> $log_status
        fi
    fi
    ############################## END: get chassis serial number by restful interface, added 2018-08-18 ##############################

    # Get FW type
    trytime=1
    echo -e "\n\nGet FW type..." >> $log_status
    while(( $trytime <= $maxtime ))
    do
        echo "try=$trytime" >> $log_status
        echo -e "start: `date`" >> $log_status
        curlresult2=`curl -c $cookies -b $cookies -H "X-CSRFToken:${token}" $IP/api/maintenance/firmware/type -i --connect-timeout 30 -S 2>>$log_status`
        echo $curlresult2 >> $log_status
        echo -e "end: `date`" >> $log_status
        getFWresult=`echo $curlresult2 |grep "\"cc\":\s*0"`
        if [[ "$getFWresult" == "" ]]; then   # Get FW Type failed, try again
            if (( $trytime == $maxtime )); then
                echo "update $IP $FWTYPE FW failed, check network env, login info and HDM state is OK or not" >> $log_status
                return 1
            fi
            echo "HDM state is abnormal, after $intervaltime_max(s) later, try again!!!" >> $log_status
            sleep $intervaltime_max
            let trytime++
        else
            echo "Get FW type success!" >> $log_status
            break
        fi
    done
    sleep 2

    # Post FW type, Put flash, Post file, Get verification
    # check the flash state of HDM to judge these 4 operations are successful or not
    echo -e "\n\nPrepare flash(including Post FW type, Put flash, Post file and Get verification)..." >> $log_status
    for (( trytime = 1; trytime <= $maxtime; trytime++ )); do
        flash_result=true
        echo -e "\ntry=$trytime" >> $log_status

        # Post FW type
        echo "Post FW type..." >> $log_status
        echo -e "start: `date`" >> $log_status
        # modified by c14146, 2018-09-29, reboot manually after upgrading, modified 2018-11-06, Des: only HDM reboot manually
        if [[ "$FWTYPE" == "HDM" ]]; then
            curlresult3=`curl -c $cookies -b $cookies -H "X-CSRFToken:${token}" -H "Content-type: application/json" -X POST -d '{"preserve_config": "'"$KEEPCONF"'", "fw_type_name": "'"$FWTYPE"'", "reboot_time": 0, "reboot_type": "'"$noreboot"'"}' $IP/api/maintenance/firmware/type -i --connect-timeout 30 -S 2>>$log_status`
        elif [[ "$FWTYPE" == "BIOS" ]]; then
            curlresult3=`curl -c $cookies -b $cookies -H "X-CSRFToken:${token}" -H "Content-type: application/json" -X POST -d '{"preserve_config": "'"$KEEPCONF"'", "fw_type_name": "'"$FWTYPE"'", "reboot_time": 0, "reboot_type": "'"$REBOOT"'"}' $IP/api/maintenance/firmware/type -i --connect-timeout 30 -S 2>>$log_status`            
        fi
        echo $curlresult3 >> $log_status
        echo -e "end: `date`" >> $log_status
        postFWresult=`echo $curlresult3 |grep "\"cc\":\s*0"`
        ### BEGIN: Modified by c14146, 2018-10-29, Des: update BIOS after OS power down ###
        postFWresult1007=`echo $curlresult3 |grep "\"cc\":\s*1007"`
        if [[ "$postFWresult" == "" ]] && [[ "$postFWresult1007" == "" ]]; then   # HDM state is not OK, go to the first step
            ### BEGIN: added 2018-09-18, Des: show the progress of post file and flash FW or not ###
            if (( $VISIBLE != 0 )); then
                echo -e "\nPost FW type failed, try again"
            fi
            ### END: added 2018-09-18, Des: show the progress of post file and flash FW or not ###
            fun_goto_first_step
            if (( $? == 0 )); then
                echo -e "\npost FW type to post FW type" >> $log_status
                continue
            else
                echo -e "\npost FW type failed" >> $log_status
                return 1
            fi
        fi
        if [[ "$postFWresult1007" != "" ]]; then
            echo -e "\nabandon the last upgrading flow, start a new upgrading flow" >> $log_status
        fi
        ### END: Modified by c14146, 2018-10-29, Des: update BIOS after OS power down ###
        sleep 2
        ### BEGIN: added 2018-09-18, Des: show the progress of post file and flash FW or not ###
        if (( $VISIBLE != 0 )); then
            echo -e "\nPost FW type success"
        fi
        ### END: added 2018-09-18, Des: show the progress of post file and flash FW or not ###

        # Put flash
        echo -e "\nPut flash..." >> $log_status
        echo -e "start: `date`" >> $log_status
        ####
        image_file=`echo $FWNAME |awk -F '@' '{print$2}'`
        image_size=`ls -l $image_file |awk '{print$5}' |sed 's/ //g'`
        command="curl -c $cookies -b $cookies -H "X-CSRFToken:${token}" -X PUT -d '{"ima_size": "'"$image_size"'"}' $IP/api/maintenance/flash -i --connect-timeout 30 -S"
        echo $command >> $log_status
        ####
        curl -c $cookies -b $cookies -H "X-CSRFToken:${token}" -X PUT -d '{"ima_size": "'"$image_size"'"}' $IP/api/maintenance/flash -i --connect-timeout 30 -S > $tmp_cmd_reply 2>>$log_status
        #curl -c $cookies -b $cookies -H "X-CSRFToken:${token}" -X PUT -d "" $IP/api/maintenance/flash -i --connect-timeout 30 -S > $tmp_cmd_reply 2>>$log_status
        fun_check_cur_reply
        result=$?
        if (( $result != 0 )); then   # HDM state is not OK, go to the first step
            fun_goto_first_step
            if (( $? == 0 )); then
                echo -e "\nput flash to post FW type" >> $log_status
                continue
            else
                echo -e "\nput flash failed" >> $log_status
                return 1
            fi
        fi
        sleep 2

        # Post file
        echo -e "\nPost file..." >> $log_status
        echo -e "start: `date`" >> $log_status
        if (( $VISIBLE == 0 )); then
            curlresult5=`curl -c $cookies -b $cookies -H "X-CSRFToken:${token}" -F $FWNAME $IP/api/maintenance/firmware -i --connect-timeout 60 -S 2>>$log_status`
        else
            echo -e "\nPost firmware file progress:"
            curlresult5=`curl -c $cookies -b $cookies -H "X-CSRFToken:${token}" -F $FWNAME $IP/api/maintenance/firmware -i --connect-timeout 60 -S`
        fi
        echo $curlresult5 >> $log_status
        echo -e "end: `date`" >> $log_status
        postresult=`echo $curlresult5 |grep "\"cc\":\s*0"`
        if [[ "$postresult" == "" ]]; then   # Post file is not OK, go to the first step
            fun_goto_first_step
            if (( $? == 0 )); then
                echo -e "\npost file to post FW type" >> $log_status
                continue
            else
                echo -e "\npost file failed" >> $log_status
                return 1
            fi
        fi
        sleep 10

        # Get verification
        echo -e "\nGet verification..." >> $log_status
        echo -e "start: `date`" >> $log_status
        curlresult6=`curl -c $cookies -b $cookies -H "X-CSRFToken:${token}" $IP/api/maintenance/firmware/verification -i --connect-timeout 30 -S 2>>$log_status`
        echo $curlresult6 >> $log_status
        echo -e "end: `date`" >> $log_status
        verifyresult=`echo $curlresult6 |grep "\"cc\":\s*0"`
        if [[ $verifyresult == "" ]]; then   # Get verify is not OK, go to the first step
            ### BEGIN: added 2018-09-18, Des: show the progress of post file and flash FW or not ###
            if (( $VISIBLE != 0 )); then
                echo -e "\nGet verification failed, try again"
            fi
            ### END: added 2018-09-18, Des: show the progress of post file and flash FW or not ###
            fun_goto_first_step
            if (( $? == 0 )); then
                echo -e "\nget verify to post FW type" >> $log_status
                continue
            else
                echo -e "\nget verify failed" >> $log_status
                return 1
            fi
        fi
        sleep 2
        ### BEGIN: added 2018-09-18, Des: show the progress of post file and flash FW or not ###
        if (( $VISIBLE != 0 )); then
            echo -e "\nGet verification success"
        fi
        ### END: added 2018-09-18, Des: show the progress of post file and flash FW or not ###

        ############################## BEGIN: Added by c14146, 2018-08-21, Des: upgrade FW and login Web is or not OK ##############################
        if [[ "$FWTYPE" == "HDM" ]]; then
            # target fw
            target_fw=`echo $curlresult6 |grep -Po '"new_image_version"\s*:\s*"[.\w]+"'`
            hdm_target_fw=`echo $target_fw |awk -F ': ' '{print$2}' |sed 's/"//g'`
        fi
        ############################## END: Added by c14146, 2018-08-21, Des: upgrade FW and login Web is or not OK ##############################
        
        # except HDM state problem, get the flash state to verify is up operations executed successfully
        fun_get_flash_step "2"
        if (( $? == 0 )); then
            echo -e "\nPrepare flash(including Post FW type, Put flash, Post file and Get verification) success, next to flash $FWTYPE!" >> $log_status
        else
            fun_goto_first_step
            if (( $? == 0 )); then
                echo -e "\nget step 2 to post FW type" >> $log_status
                continue
            else
                echo -e "\nget step 2 failed" >> $log_status
                return 1
            fi
        fi
        sleep 2

        # Put upgrade
        echo -e "\nPut upgrade..." >> $log_status
        echo -e "start: `date`" >> $log_status
        curlresult7=`curl -c $cookies -b $cookies -H "X-CSRFToken:${token}" -H "Content-type: application/json" -X PUT -d '{"flash_status": 1}' $IP/api/maintenance/firmware/upgrade -i --connect-timeout 30 -S 2>>$log_status`
        echo $curlresult7 >> $log_status
        echo -e "end: `date`" >> $log_status
        upgraderesult=`echo $curlresult7 |grep "\"cc\":\s*0"`
        if [[ $upgraderesult == "" ]]; then   # Put upgrade is not OK, go to the first step
            fun_goto_first_step
            if (( $? == 0 )); then
                echo -e "\nput upgrade to post FW type" >> $log_status
                continue
            else
                echo -e "\nput upgrade failed" >> $log_status
                return 1
            fi
        fi
        ## BEGIN: Modified by c14146, 2018-10-29, Des: update BIOS after OS power down ###
        echo -e "\nPut upgrade success, start to flash $FWTYPE!" >> $log_status
        : '
        sleep 2
        fun_get_flash_step "3"
        if (( $? == 0 )); then
            echo -e "\nPut upgrade success, start to flash $FWTYPE!" >> $log_status
        else
            fun_goto_first_step
            if (( $? == 0 )); then
                echo -e "\nget step 3 to post FW type" >> $log_status
                continue
            else
                echo -e "\nget step 3 failed" >> $log_status
                return 1
            fi
        fi
        '
        ## END: Modified by c14146, 2018-10-29, Des: update BIOS after OS power down ###
        sleep 2

        break
    done

    if (( $trytime > $maxtime )); then
        return 1
    fi

    # Get flash process
    echo -e "\nGet flash process..." >> $log_status
    MAXLOOP=60
    cnt=0
    echo > $tmp_cmd_reply
    ### BEGIN: modified 2018-09-18, Des: show the progress of post file and flash FW or not ###
    flagnum=0
    flagindex=0
    bar=''
    flagfirst=true
    while [[ `cat $tmp_cmd_reply |grep -i "Complete"` == "" ]]
    do
        echo > $tmp_cmd_reply
        curl -c $cookies -b $cookies -H "X-CSRFToken:${token}" $IP/api/maintenance/firmware/flash_progress -i --connect-timeout 30 -s > $tmp_cmd_reply 2>>$log_status
        echo -e "`cat $tmp_cmd_reply`\n" >> $log_status
        sleep 3
        let cnt++
        ### BEGIN: Added by c14146, 2018-10-29, Des: update BIOS after OS power down ###
        if [[ `cat $tmp_cmd_reply |grep -i "Update Waiting"` != "" ]]; then
            echo -e "\nFirmware submit successfully, BIOS will be updated while OS power down" >> $log_status
            IsUpdateNext=true
            return 0
        fi
        ### END: Added by c14146, 2018-10-29, Des: update BIOS after OS power down ###
        if (( $cnt > $MAXLOOP )); then
            echo -e "\nuable to get the flash process!" >> $log_status
            flash_result=false
            break
        fi
        if (( $VISIBLE != 0 )); then
            if $flagfirst; then
                echo -e "\nFlash firmware progress:"
            fi
            flagfirst=false
            flagnum=`cat $tmp_cmd_reply |grep -Po '"progress": "[\d]+' |awk -F ': "' '{print$2}'`
            if [[ "$flagnum" != "" ]]; then
                while [[ $flagindex -le $flagnum ]];
                do
                    printf "[%-100s][%d%%]\r" "$bar" "$flagindex"
                    let flagindex++
                    bar+='#'
                done
            fi
        fi
    done

    if $flash_result; then
        if (( $VISIBLE != 0 )); then
            while [[ $flagindex -lt 100 ]];
            do
                let flagindex++
                printf "[%-100s][%d%%]\r" "$bar" "$flagindex"
                bar+='#'
            done
            printf "\n"
        fi
        return 0
    else
        printf "\n"
        return 1
    fi
    ### END: modified 2018-09-18, Des: show the progress of post file and flash FW or not ###

}


### fun_one_time_upgrade
for (( flow_time = 1; flow_time <= 3; flow_time++ )); do
    fun_one_time_upgrade
    if (( $? == 1 )); then
        echo "`date`" >> $log_status
        echo -e "\n$IP after 300s, execute the upgrade flow again" >> $log_status
        sleep 300
    else
        ############################## BEGIN: Added by c14146, 2018-08-21, Des: upgrade FW and login Web is or not OK ##############################
        hdm_version_flag=false
        if (( $REBOOT == 0 )) && [[ "$FWTYPE" == "HDM" ]] && ( ! $IsUpdateNext ); then   ### Modified by c14146, 2018-10-29, Des: update BIOS after OS power down

            ### BEGIN: Added by c14146, 2018-09-29, Des: HDM 1.00.26P01 not support reboot automatically ###
            # 2018-11-27, Des: Add reboot logging
            echo -e "\nReboot HDM..." >> $log_status
            echo -e "start: `date`" >> $log_status
            curlresultReboot=`curl -c $cookies -b $cookies -H "X-CSRFToken:${token}" -H "Content-type: application/json" -X POST -d '{"reset": 1}' $IP/api/maintenance/restore_hdm -i --connect-timeout 30 -S 2>>$log_status`
            echo $curlresultReboot >> $log_status
            echo -e "end: `date`" >> $log_status
            rebootresult=`echo $curlresultReboot |grep "\"cc\":\s*0"`
            if [[ $rebootresult == "" ]]; then
                echo -e "\nReboot HDM failed, $IP after 30, execute the upgrade flow again" >> $log_status
                sleep 30
                continue
            else
                echo -e "\n\nafter upgrading $FWTYPE FW, reboot HDM, please wait 360s..." >> $log_status
                sleep 360
            fi
            ### END: Added by c14146, 2018-09-29, Des: HDM 1.00.26P01 not support reboot automatically ###
            
            ### check login Web is OK or not
            for (( check_time = 1; check_time <= 3; check_time++ )); do
                hdm_version_flag=false
                # Establish session
                token=""
                fun_establish_session
                session_result_check=$?
                if (( $session_result_check != 0 )); then
                    echo -e "\nafter upgrading HDM and reboot, HDM status seems abnormal, reboot HDM again!!!" >> $log_status
                    ipmitool -I lanplus -H $IP -U $USER -P $PWD mc reset cold
                    if (( $? == 0 )); then
                        echo "reboot HDM, please wait 360s..." >> $log_status
                        sleep 360
                        continue
                    else
                        echo "reboot HDM failed!!!" >> $log_status
                        continue
                    fi
                fi
                ### get the main/back HDM version
                echo -e "\n\nget the main/back HDM version..." >> $log_status
                echo -e "start: `date`" >> $log_status
                curresult_hdm_verison=`curl -c $cookies -b $cookies -H "X-CSRFToken:${token}" $IP/api/maintenance/primary_backup_version -i --connect-timeout 30 -S 2>>$log_status`
                echo "$curresult_hdm_verison" >> $log_status
                echo -e "end: `date`" >> $log_status
                # primary HDM fw
                primary_fw=`echo $curresult_hdm_verison |grep -Po '"primary_version"\s*:\s*"[.\w]+"' |awk -F ': ' '{print$2}' |sed 's/"//g'`
                echo "primary hdm fw: $primary_fw, target hdm fw: $hdm_target_fw" >> $log_status
                if [[ "$primary_fw" != "$hdm_target_fw" ]]; then
                    echo -e "\nafter upgrading HDM and reboot, HDM version is not changed, try upgrade HDM FW again!!!" >> $log_status
                    hdm_version_flag=true
                    break
                else
                    break
                fi
            done
            if (( $check_time > 3 )); then
                echo -e "\n$IP FW upgrade failed for $FWTYPE $MAINBACK image, check network env, login info and HDM state is OK or not, the SN of the server is: $SN" |tee -a $log_status   # added 2018-09-13, Des: terminal log
                exit 1
            fi
        fi
        if $hdm_version_flag; then
            continue
        fi
        ############################## END: Added by c14146, 2018-08-21, Des: upgrade FW and login Web is or not OK ##############################
        echo -e "\n$IP FW upgrade finished for $FWTYPE $MAINBACK image" |tee -a $log_status   # added 2018-09-13, Des: terminal log
        echo "the SN of the server is: $SN" >> $log_status
        echo "`date`" >> $log_status
        exit 0
    fi
done

echo -e "\n$IP FW upgrade failed for $FWTYPE $MAINBACK image, check network env, login info and HDM state is OK or not, the SN of the server is: $SN" |tee -a $log_status   # added 2018-09-13, Des: terminal log
exit 1
