#!/bin/bash

declare -r fi_update_work="/opt/fiupdate"
declare fi_update_log=''
declare work_curPath=''
declare pro_info="NCE_info"
declare product_dir='/opt/fiupdate/NCE_info'
declare fiweb=''
declare mainOms=''
declare analyzer_scene=''
declare analyzer_scale=''
declare update_config=''
declare real_config=''
declare real_dir=''
declare root_pwd=''
declare admin_pwd=''
declare mode=''
declare backupOms=''
declare ODAAEplugin=''
declare fi_version=''

TMOUT=0
User_ID=`/usr/bin/id -u`
if [ $User_ID -ne 0 ] 
then
    echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] run user must be root"
    exit 1
fi

read -s -p "please input ossadm password:" ossadm_pwd
echo -e "\n"

read -s -p "please input root password:" root_pwd
echo -e "\n"

read -s -p "please input FI admin password:" admin_pwd
echo -e "\n"

ossadm_pwd=$(perl -e 'print quotemeta shift(@ARGV)' "${ossadm_pwd}")
root_pwd=$(perl -e 'print quotemeta shift(@ARGV)' "${root_pwd}")
admin_pwd=$(perl -e 'print quotemeta shift(@ARGV)' "${admin_pwd}")

ODAAEpluginfile=`find ${fi_update_work}/package/ -name "ODAESwiftDeployPlugin*.zip" -type f`
ODAAEplugin=`basename ${ODAAEpluginfile}`

function get_cur_path()
{
    cd "$(dirname "${BASH_SOURCE-$0}")"
    work_curPath="${PWD}"
    fi_scriptName="$(basename "${BASH_SOURCE-$0}")"
    cd - >/dev/null
}

logDef()
{
    local funcName="$1"; shift
    local logLevel="$1"; shift
    local lineNO="$1"; shift

    local logTime="$(date -d today +'%Y-%m-%d %H:%M:%S')"
    printf "[${logTime}] ${logLevel} $* [${g_scriptName}(${funcName}):${lineNO}]($$)\n" \
        >> "${fi_update_log}" 2>&1
}

log_error()
{
    logDef "${FUNCNAME[1]}" "ERROR" "$@"
}

log_info()
{
    logDef "${FUNCNAME[1]}" "INFO" "$@"
}

function init_log()
{
    if [ ! -d "$fi_update_work/log" ]
    then
        mkdir "$fi_update_work/log"
    fi
    fi_update_log="$fi_update_work/log/update_cluster.log"
    [ ! -f "${fi_update_log}" ] && touch "${fi_update_log}"
    chmod 600 "${fi_update_log}"
    echo > ${fi_update_log}
    
}

trap 'onCtrlC' INT
function onCtrlC () {
    echo 'exit program'
    exit 1
}

function output_info()
{
    cd ${fi_update_work}
    if [ -d ${pro_info} ]
    then
        rm -fr ${pro_info}
    fi
    mkdir ${pro_info}
    if [ ! -f "/opt/oss/manager/tools/resmgr/queryproduct.sh" ]
    then
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] platform queryproduct script not exists,please check"
        log_error "${LINENO}" "platform queryproduct script not exists,please check"
        return 1
    fi

    if [ ! -f "/opt/oss/manager/tools/resmgr/modifynodesinfo.sh" ]
    then
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] platform modifynode script not exists,please check"
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] platform modifynode script not exists,please check" >> $Modify_LOG
        return 1
    fi

    if [ ! -f "/opt/oss/manager/tools/resmgr/modifyproductinfo.sh" ]
    then
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] platform modifyproduct script not exists,please check"
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] platform modifyproduct script not exists,please check" >> $Modify_LOG
        return 1
    fi
    
    if [ ! -f "/opt/oss/manager/var/tenants/NCE/nodelist.json" ]
    then
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] platform nodelist json not exists,please check"
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] platform nodelist json not exists,please check" >> $Modify_LOG
        return 1
    fi

    echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] Start to output node and product information"
    echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] Start to output node and product information" > $Modify_LOG
    cd /opt/oss/manager/tools/resmgr/
    echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] Start to modify node and product information"
    echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] Start to modify node and product information" >> $Modify_LOG
    sh queryproduct.sh -pn NCE -output $ModifyWork
    if [ $? -ne 0 ] 
    then
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] output node and product information failed"
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] output node and product information failed" >> $Modify_LOG
        return 1
    fi
    echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] output node and product information success"
    echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] output node and product information success" >> $Modify_LOG
}

function set_premeters()
{

    product_name=$1
    if [ ! -f "/opt/fiupdate/NCE_info/nodes_${product_name}.ini" ]
    then
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] $product_name: FI nodes config file not exists,please check"
        log_error "${LINENO}" "$product_name: platform nodelist json not exists,please check"
        return 1
    fi
    mainOms=`cat /opt/fiupdate/NCE_info/nodes_${product_name}.ini |grep mainOms= |sed 's/mainOms=//g'`
    analyzer_scene=`cat /opt/fiupdate/NCE_info/nodes_${product_name}.ini|grep feature |sed 's/feature=//g'|awk -F ';' '{print $1}'`
    analyzer_scene=`echo $analyzer_scene | tr A-Z a-z`
    analyzer_scale=`cat /opt/fiupdate/NCE_info/nodes_${product_name}.ini|grep feature |sed 's/feature=//g'|awk -F ';' '{print $2}'`
    analyzer_scale=`echo $analyzer_scale | tr A-Z a-z`
    fiweb=`cat /opt/fiupdate/NCE_info/nodes_${product_name}.ini|grep fiweb | sed  's/fiweb=//g'`
    mode=`cat /opt/fiupdate/NCE_info/nodes_${product_name}.ini |grep mode= |sed 's/mode=//g'`
    fi_version=`cat /opt/fiupdate/NCE_info/nodes_${product_name}.ini |grep fi_version= |sed 's/fi_version=//g'`
    
    if [ "$mode" == "double" ]
    then
        backupOms=`cat /opt/fiupdate/NCE_info/nodes_${product_name}.ini |grep backupOms= |sed 's/backupOms=//g'`
    fi
    return 0
}

function locksafe()
{
    product_name=$1
    echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] $product_name : all FI nodes need to restore safe mode "
    log_info "${LINENO}" " $product_name : all FI nodes need to restore safe mode "
    if [ ! -f "/opt/fiupdate/safelock.sh" ]
    then
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] $product_name : restore safe mode script not exists"
        log_error "${LINENO}" " $product_name : restore safe mode script not exists "
        return 1
    fi
    
    cd /opt/fiupdate
    expect <<END
        spawn  bash safelock.sh
        expect "*assword:"
            send "$root_pwd\r"
        set timeout 1200
        expect eof
END
   
    return 0
}

function CheckPwd()
{

    if [[ $root_pwd =~ " " ]]
    then
        echo "[`date '+%Y-%m-%d %H:%M:%S'`] the root password you input is valid" 
        return 1
    fi
    
    if [[ $admin_pwd =~ " " ]]
    then
        echo "[`date '+%Y-%m-%d %H:%M:%S'`] the FI admin password you input is valid" 
        return 1
    fi
       
    return 0
    
}


function CheckUser()
{
    User_ID=`/usr/bin/id -u`
    if [ $User_ID -ne 0 ] 
    then
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] run user must be root"
        log_error "${LINENO}" "run user must be root"
        return 1
    fi
    return 0
}


function runupd()
{
    product_name=$1
    echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] $product_name : run ODAE update cluster script in ${mainOms}"
    log_info "${LINENO}" " $product_name : run ODAE update cluster script in ${mainOms}"
    expect <<END
        spawn ssh -t ossadm@${mainOms} " cd /opt/fiupdate;bash update_cluster_fi_ossadm.sh"
        expect {
            "*yes/no*" {send "yes\r";exp_continue}
            "assword:" {send "$ossadm_pwd\r"}
        }
        expect "*assword:"
            send "$root_pwd\r"
        expect "*assword:"
            send "$admin_pwd\r"
        set timeout 1200
        expect eof
END

    echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] $product_name : start to get update cluster result "
    log_info "${LINENO}" " $product_name : start to get update cluster result "
    expect <<END
        spawn scp -p ossadm@${mainOms}:/opt/fiupdate/log/update_cluster_8021.log  /opt/fiupdate/log/
        expect {
            "*yes/no*" {send "yes\r";exp_continue}
            "assword:" {send "$ossadm_pwd\r"}
        }
        set timeout 600
        expect eof
END
    
    if [ ! -f "/opt/fiupdate/log/update_cluster_8021.log" ]
    then
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] $product_name : update cluster Run Failed "
        log_error "${LINENO}" " $product_name : update cluster Run Failed "
        return 1
    fi
    
    runresult=`cat /opt/fiupdate/log/update_cluster_8021.log | grep 'update cluster stage work success'`
    
    if [ ! -n "$runresult" ]
    then
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`]  $product_name : update cluster Run Failed "
        log_error "${LINENO}" " $product_name : update cluster Run Failed "
        return 1
    fi
    
    echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] $product_name : update cluster Run Success "
    log_info "${LINENO}" " $product_name : update cluster Run Success "
    
    return 0
}

function restartODAE()
{
    echo "[`date '+%Y-%m-%d %H:%M:%S'`] start to restart all FI nodes ODAE services"
    log_info "${LINENO}" "start to restart all FI nodes ODAE services"
    
    if [ ! -f "${fi_update_work}/restart_odae.sh" ]
    then
        echo "[`date '+%Y-%m-%d %H:%M:%S'`] restart odae services script not exists,please check"
        log_error "${LINENO}" "restart odae services script not exists,please check"
    fi
    
    if [ ! -f "${fi_update_work}/restart_odae_fi.sh" ]
    then
        echo "[`date '+%Y-%m-%d %H:%M:%S'`] restart odae services script not exists,please check"
        log_error "${LINENO}" "restart odae services script not exists,please check"
    fi
    
    cd  $fi_update_work/
    
    expect <<END
    spawn bash restart_odae.sh
    expect "*assword:"
        send "$ossadm_pwd\r"
    expect "*assword:"
        send "$root_pwd\r"
    set timeout -1
    expect eof
END
      
    return 0 
}

function unset_parameters()
{
    unset admin_pwd
    unset root_pwd
    unset fiweb
}


function Main()
{
    log_info "${LINENO}" "update fi cluster parameters"
    CheckUser
    if [ $? -ne 0 ]
    then
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] check run user failed"
        log_error "${LINENO}" "check run user failed"
        return 1
    fi
    CheckPwd    
    if [ $? -ne 0 ]
    then
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] check input password failed"
        log_error "${LINENO}" "check input password failed"
        return 1
    fi
    
    if [ ! -d "$product_dir" ]
    then
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] product conf dir not exists ,please run safeunlock.sh"
        log_error "${LINENO}" "product conf dir not exists ,please run safeunlock.sh"
        return 1
    fi
    product_all=`find $product_dir/ -name "node*.ini" -type f`
    for i in ${product_all}
    do
    {
        product_one=$(basename $i .ini|sed 's/nodes_//g')
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] Start to do $product_one product"
        log_info "${LINENO}" "Start to do $product_one product"
        break_out=`cat $i|grep 'updcluster=0'`
        if [ -n "${break_out}" ]
        then
            echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] config show $product_one product break update cluster stage"
            log_info "${LINENO}" " config show $product_one product break update cluster stage"
            continue
        else
            echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] config show $product_one product not break update cluster stage"
            log_info "${LINENO}" " config show $product_one product not break update cluster stage"
        fi
        set_premeters $product_one
        if [ $? -ne 0 ]
        then
            echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] $product_one: update cluster set parameters failed"
            log_error "${LINENO}" "update cluster set parameters failed"
            return 1
        fi
        
        runupd $product_one
        if [ $? -ne 0 ]
        then
            echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] $product_one: update cluster run odae script failed"
            log_error "${LINENO}" " $product_one: update cluster run odae  script failed"
            return 1
        fi
    }
    done
    
    echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] update cluster run success"
    log_info "${LINENO}" "update cluster run success"
     
    restartODAE
    if [ $? -ne 0 ]
    then
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] restart ODAE services job failed"
        log_error "${LINENO}" " restart ODAE services job failed"
        return 1
    fi
    
    echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] \033[42;34m update FI parameters success \033[0m"
    log_info "${LINENO}" "update FI parameters success"
    
    return 0
         
}

config_name=$1
get_cur_path
cd "${work_curPath}"

init_log || return $?

Main
mainresult=$?
unset_parameters
exit $mainresult
