#! /bin/bash

log_file="checkexitupdate.log"
fi_update_work="/opt/fiupdate"
GetWorkPath()
{
    dir=`/usr/bin/dirname $0`
    ispoint=`/bin/echo $dir| /usr/bin/awk -F/ '{print $1}'`
    if [ "$ispoint" = "." ]
    then
        dir=`/bin/echo $dir|/usr/bin/sed 's/^.//'`
        curpath="`pwd`$dir"
    elif [ "$ispoint" = ".." ]
    then
        curpath="`pwd`/$dir"
    else
       curpath="$dir"
    fi
    mkdir -p $curpath/log
    touch $curpath/log/$log_file
    echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] Begin Check ExitUpdatePeriod..." >> $curpath/log/$log_file

    return 0
}
Unlock()
{
    cd /opt/fiupdate
    expect <<END
    spawn bash safeunlock.sh
    expect {
        "please input ossadm password:" {send "$ossadm_pwd\r"}
    }
    expect {
        "please input root password:" {send "$root_pwd\r"}
    }
    expect {
        "please input FI admin password:" {send "$admin_pwd\r"}
    }
    set timeout 1200
    expect "*#"
    exit
END
}

CheckExitUpdate()
{
    if [ ! -f /opt/huawei/Bigdata/update-service/data/*/result/UpdateService/ExitUpdatePeriod.rst ]
    then
        echo "[`date '+%Y-%m-%d %H:%M:%S'`]ExitUpdatePeriod.rst not exists, do not config." >> $curpath/log/$log_file
        return 0
    fi
    ExitUpdatePeriod=/opt/huawei/Bigdata/update-service/data/*/result/UpdateService/ExitUpdatePeriod.rst
    taskid=`echo $ExitUpdatePeriod | awk -F "/" {'print $7'}`
    node_state=`cat $ExitUpdatePeriod | grep "NODE_STATE_FAIL"`
    if [ ! -n "$node_state" ]
    then
        echo "ExitUpdatePeriod does not fail, do nothing." >> $curpath/log/$log_file
        return 0
    fi
    update_mode=`curl -s -X GET "http://127.0.0.1:20008/update/v1/clusters/1/update_mode/action/query"`
    if [ "x${update_mode}" == "xfalse" ]
    then
        echo "Check whether the update_mode status is normal, do nothing." >> $curpath/log/$log_file
        return 0
    elif [ "x${update_mode}" == "xtrue" ]
    then
        curl -H "Content-Type:application/xml" -X POST -d "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><updateModeRequest><project><id>${taskid}</id><type>UPGRADE</type></project></updateModeRequest>" http://127.0.0.1:20008/update/v1/clusters/1/update_mode/action/disable > /dev/null 2>&1
    fi
    update_modes=`curl -s -X GET "http://127.0.0.1:20008/update/v1/clusters/1/update_mode/action/query"`
    if [ "x${update_modes}" == "xfalse" ]
    then
        echo "Disabling update_mode action succeeded, do nothing." >> $curpath/log/$log_file
        return 0
    elif [ "x${update_modes}" == "xtrue" ]
    then
        modify_om_clusters
    fi

}

modify_om_clusters()
{
    update_mode_result=`su - omm -c "gsql -p 20015 -U omm -W ${gsql_pwd} -c \"select UPDATE_MODE from om_clusters;\""`
    update_mode_result=`echo $update_mode_result | awk -F " {" {'print $2'} | awk -F "}}" {'print $1'}`
    update_mode_result=${update_mode_result/true/false}
    update_mode_sql={${update_mode_result}}}
    sql="update om_clusters set UPDATE_MODE='${update_mode_sql}';"
    exc_sql=${sql//'"'/'\"'}
    su - omm -c "gsql -p 20015 -U omm -W ${gsql_pwd} -c \"${exc_sql}\"" >> $curpath/log/$log_file
    su - omm -c "bash /opt/huawei/Bigdata/om-server/om/sbin/stop-controller.sh" >> $curpath/log/$log_file
    su - omm -c "bash /opt/huawei/Bigdata/om-server/om/sbin/start-controller.sh" >> $curpath/log/$log_file
    update_mode=`curl -s -X GET "http://127.0.0.1:20008/update/v1/clusters/1/update_mode/action/query"`
    for ((j=1;j<=20;j++))
    do 
        if [ "x${update_mode}" != "xfalse" ]
        then
            echo "[`date '+%Y-%m-%d %H:%M:%S'`]---check update_mode action $j times, please wait..." >> $curpath/log/$log_file
            sleep 10
            update_mode=`curl -s -X GET "http://127.0.0.1:20008/update/v1/clusters/1/update_mode/action/query"`
        else
            echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] The update_mode is successfully modified and the update_mode status is normal, retry to update FusionInsight..." >> $curpath/log/$log_file
            break
        fi
    done
}

decompress_package()
{
    echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] begin Check whether the software package is decompressed..." >> $curpath/log/$log_file
    product_dir='/opt/fiupdate/NCE_info'
    product_all=`find $product_dir/ -name "nodes_*.ini" -type f`
    for product_ini in ${product_all}
    do
    {
        product_one=$(basename $product_ini .ini|sed 's/nodes_//g')
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] Start to check the FI of $product_one product" >> $curpath/log/$log_file
        rm -rf iptmp.conf > /dev/null 2>&1
        cat $product_ini |grep finode= |sed 's/finode=//g' >>./iptmp.conf
        cat $product_ini |grep Analyzer_Calc_Storage | awk -F "=" {'print $2'} >>./iptmp.conf
        fi_nodes=`sort -u iptmp.conf`
        for fi_node in ${fi_nodes}
        do        
        expect <<END
                    spawn scp -p /opt/fiupdate/pre_config.sh root@${fi_node}:/opt
                    expect {
                    "*yes/no*" {send "yes\r";exp_continue}
                    "assword:" {send "$root_pwd\r"}
                    }
                    set timeout 600
                    expect eof
END

        expect <<END
                    spawn ssh -t root@${fi_node} "cd /opt/ ; bash pre_config.sh decompress ; rm -rf /opt/pre_config.sh > /dev/null 2>&1"
                    expect {
                    "*yes/no*" {send "yes\r";exp_continue}
                    "assword:" {send "$root_pwd\r"}
                    }
                    set timeout 600
                    expect eof
END

        done
        rm -rf iptmp.conf > /dev/null 2>&1
    }
    done
}

Main()
{
    gsql_pwd=$1
    root_pwd=$2
    ossadm_pwd=$3
    admin_pwd=$4
    root_pwd=$(perl -e 'print quotemeta shift(@ARGV)' "${root_pwd}")
    ossadm_pwd=$(perl -e 'print quotemeta shift(@ARGV)' "${ossadm_pwd}")
    admin_pwd=$(perl -e 'print quotemeta shift(@ARGV)' "${admin_pwd}")
    GetWorkPath
    # 如果和NCE并行升级，有可能FI升级期间root又被禁止登录了，重新启用root登录来修改FI参数
    Unlock
    unlockResult=`cat ${fi_update_work}/log/unlock_safe.log | grep "script in stage unlock all FI nodes success"`
    if [ "x${unlockResult}" == "x" ]
    then
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] \033[41;30m Safe unlock is failed. \033[0m"
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] Safe unlock is failed." >> $curpath/log/$log_file
        return 1
    else
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] \033[42;34m Safe unlock is success. \033[0m"
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] Safe unlock is success." >> $curpath/log/$log_file
    fi
    CheckExitUpdate
    decompress_package
}

Main $*
exit $?
