#!/bin/bash

declare -r fi_update_work="/opt/fiupdate"
declare fi_update_log=''
declare work_curPath=''
declare pro_info="NCE_info"
declare fiweb=''
declare analyzer_scene=''
declare analyzer_scale=''
declare update_config=''
declare oms_config=''
declare real_config=''
declare real_dir=''
declare root_pwd=''
declare admin_pwd=''
declare mainOms=''
declare odae_work='/opt/fiupgrade'
declare SysVer
declare SysVerDetail
declare analyzer_nodes=''
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 root password:" root_pwd
echo -e "\n"

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

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

SysVerInfo=`cat /etc/os-release`
if [[ "$SysVerInfo" =~ "SLES" ]]; then
    echo "[`date '+%Y-%m-%d %H:%M:%S'`] system is SUSE"
    SysVer="SUSE"
    if [[ "$SysVerInfo" =~ "12.2" ]];then
        echo "[`date '+%Y-%m-%d %H:%M:%S'`] system is SUSE12SP2" 
        SysVerDetail="SUSE12SP2"
    elif [[ "$SysVerInfo" =~ "12.4" ]];then
        echo "[`date '+%Y-%m-%d %H:%M:%S'`] system is SUSE12SP4" 
        SysVerDetail="SUSE12SP4"
    else
        echo "[`date '+%Y-%m-%d %H:%M:%S'`] system is Suse, but not SUSE12SP2 and SUSE12SP4"
        echo "[`date '+%Y-%m-%d %H:%M:%S'`] FI cannot update"
        exit 1
    fi
elif [[ "$SysVerInfo" =~ "EulerOS" ]]; then
    echo "[`date '+%Y-%m-%d %H:%M:%S'`] system is EulerOS"
    SysVer="EulerOS"
    SysVerDetail="EULER2SP5"
else
    echo "[`date '+%Y-%m-%d %H:%M:%S'`] system is not SUSE,is not EulerOS"
    echo "[`date '+%Y-%m-%d %H:%M:%S'`] FI cannot update"
    exit 1
fi

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_8021.log"
    [ ! -f "${fi_update_log}" ] && touch "${fi_update_log}"
    chmod 600 "${fi_update_log}"
    echo > ${fi_update_log}
    chown -R ossadm:ossgroup $fi_update_work/log
}

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
    return 0
}

function set_premeters()
{

    if [ ! -f "/opt/fiupdate/conf/nodes.ini" ]
    then
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] FI nodes information config not exists"
        log_error "${LINENO}" "FI nodes information config not exists"
        return 1
    fi
    analyzer_nodes=`cat /opt/fiupdate/conf/nodes.ini|grep Analyzer_Calc`
    analyzer_scene=`cat /opt/fiupdate/conf/nodes.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/conf/nodes.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/conf/nodes.ini|grep fiweb | sed  's/fiweb=//g'`
    mainOms=`cat /opt/fiupdate/conf/nodes.ini |grep mainOms= |sed 's/mainOms=//g'`
    fi_version=`cat /opt/fiupdate/conf/nodes.ini |grep fi_version= |sed 's/fi_version=//g'`
    return 0
}

function set_configfile()
{
    if [ ! -f "/opt/fiupdate/conf/FI_u2000.json" ]
    then
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] FI_u2000 config file  not exists"
        log_error "${LINENO}" "FI u2000 config file not exists"
        return 1
    fi
    sed -i "s/BigDataAnalyzer_float01_ip/$fiweb/g"  /opt/fiupdate/conf/FI_u2000.json
    update_config=$fi_update_work/conf/$analyzer_scene/$analyzer_scale/ficluster_conf.json
    oms_config=$fi_update_work/conf/$analyzer_scene/$analyzer_scale/fiscript_conf.json
    default_config=$fi_update_work/conf/ficluster_conf.json
    if [ ! -f "${update_config}" ]
    then
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] match scene scale config not exists, will do not use config folder"
        log_info "${LINENO}" "match scene scale config not exists, will do not use config folder"
		echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] update fi cluster config folder is null "
        log_info "${LINENO}" "update fi cluster config folder is null "
    else
        real_dir=$fi_update_work/conf/$analyzer_scene/$analyzer_scale/
		echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] update fi cluster config folder is $real_dir "
        log_info "${LINENO}" "update fi cluster config folder is $real_dir "
    fi
    
    return 0

}

function shield_alarm()
{
    echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] script will shield some alarm information "
    log_info "${LINENO}" "script will shield some alarm information"
    if [ -f $real_dir/shield_alarm.json ]
    then
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] user define alarm file exist $real_dir/shield_alarm.json "
        cp -f $real_dir/shield_alarm.json  ${odae_work}/ODAEDeployTool/etc/datamodel/
    else
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] use default alarm json."
        cp -f ${fi_update_work}/conf/shield_alarm.json  ${odae_work}/ODAEDeployTool/etc/datamodel/
    fi
    
    cd  ${odae_work}/ODAEDeployTool/bin

    expect <<END
    spawn bash shield_alarm.sh
    set timeout -1
    expect "*assword:"
    send "true,$admin_pwd\r"
    set timeout -1
    expect eof
END
    if [ $? -ne 0 ] 
    then
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] script shields some alarm information failed"
        log_error "${LINENO}" "script shields some alarm information failed"
        return 1
    fi
}

function set_oms_config()
{
    # FAN定制OMS内存优化参数
    if [ -f $real_dir/conf/fi_8_0_2_1_script_config_fan.json ]
    then
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] user define oms config file exist $real_dir/conf/fi_8_0_2_1_script_config_fan.json."
        change_one_paras "script_file_name" "fi_8_0_2_1_script_config_fan.json"
        echo y | cp $real_dir/conf/fi_8_0_2_1_script_config_fan.json ${odae_work}/ODAEDeployTool/etc/datamodel
        return 0
    fi    
    cat /opt/fiupdate/conf/nodes.ini | grep "mode=single" > /dev/null
    if [ $? -eq 0 ]
    then
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] user single mode oms config."
        # OMS内存优化参数
        if [ -f ${fi_update_work}/conf/fi_8_0_2_1_script_config.json ]
        then
            change_one_paras "script_file_name" "fi_8_0_2_1_script_config.json"
            echo y | cp ${fi_update_work}/conf/fi_8_0_2_1_script_config.json $odae_work/ODAEDeployTool/etc/datamodel
        fi
        return
    fi
    # 根据FI节点个数不同设置不同的OMS优化参数
    nodenum=`cat /opt/fiupdate/conf/nodes.ini |grep "finode=" | wc -l`
    nodenum=`echo $nodenum+2|bc`
    if [ $nodenum -eq 3 ]
    then
        # OMS内存优化参数
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] nodenum is equal 3 use ${fi_update_work}/conf/fi_8_0_2_1_script_config_1wuser_2kap.json."
        if [ -f ${fi_update_work}/conf/fi_8_0_2_1_script_config_1wuser_2kap.json ]
        then
            change_one_paras "script_file_name" "fi_8_0_2_1_script_config_1wuser_2kap.json"
            echo y | cp ${fi_update_work}/conf/fi_8_0_2_1_script_config_1wuser_2kap.json $odae_work/ODAEDeployTool/etc/datamodel
            perl -i -lpe "s~\"customized_conf\": \"pms.mem=1024m\"~\"customized_conf\": \"pms.mem=3072m\"~g" $odae_work/ODAEDeployTool/etc/datamodel/fi_8_0_2_1_script_config_1wuser_2kap.json
        fi
    elif [ $nodenum -gt 3 -a $nodenum -le 6 ]
    then
        # OMS内存优化参数
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] nodenum is is greater than 3 and less than 6 use ${fi_update_work}/conf/fi_8_0_2_1_script_config_1wuser_2kap.json."
        if [ -f ${fi_update_work}/conf/fi_8_0_2_1_script_config_1wuser_2kap.json ]
        then
            change_one_paras "script_file_name" "fi_8_0_2_1_script_config_1wuser_2kap.json"
            echo y | cp ${fi_update_work}/conf/fi_8_0_2_1_script_config_1wuser_2kap.json $odae_work/ODAEDeployTool/etc/datamodel
            perl -i -lpe "s~\"customized_conf\": \"pms.mem=1024m\"~\"customized_conf\": \"pms.mem=3072m\"~g" $odae_work/ODAEDeployTool/etc/datamodel/fi_8_0_2_1_script_config_1wuser_2kap.json
        fi
    elif [ $nodenum -gt 6 ]
    then
        # ip+光场景定制
        if [ "$analyzer_scene" == "ip_super_t" -a "$analyzer_scale" == "15k" ]
        then
            echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] ip_super_t and 15k use ${fi_update_work}/conf/fi_8_0_2_1_script_config_1wuser_2kap.json."
            if [ -f ${fi_update_work}/conf/fi_8_0_2_1_script_config_1wuser_2kap.json ]
            then
                change_one_paras "script_file_name" "fi_8_0_2_1_script_config_1wuser_2kap.json"
                echo y | cp ${fi_update_work}/conf/fi_8_0_2_1_script_config_1wuser_2kap.json $odae_work/ODAEDeployTool/etc/datamodel
                perl -i -lpe "s~\"customized_conf\": \"pms.mem=1024m\"~\"customized_conf\": \"pms.mem=3072m\"~g" $odae_work/ODAEDeployTool/etc/datamodel/fi_8_0_2_1_script_config_1wuser_2kap.json
                return 0
            fi
        fi
        # IP+T 30K定制
        if [ "$analyzer_scene" == "ip_t" -a "$analyzer_scale" == "30k" ]
        then
            echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] ip_t and 30k use ${fi_update_work}/conf/fi_8_0_2_1_script_config_1wuser_2kap.json."
            if [ -f ${fi_update_work}/conf/fi_8_0_2_1_script_config_1wuser_2kap.json ]
            then
                change_one_paras "script_file_name" "fi_8_0_2_1_script_config_1wuser_2kap.json"
                echo y | cp ${fi_update_work}/conf/fi_8_0_2_1_script_config_1wuser_2kap.json $odae_work/ODAEDeployTool/etc/datamodel
                perl -i -lpe "s~\"customized_conf\": \"pms.mem=1024m\"~\"customized_conf\": \"pms.mem=3072m\"~g" $odae_work/ODAEDeployTool/etc/datamodel/fi_8_0_2_1_script_config_1wuser_2kap.json
                return 0
            fi
        fi
        # OMS内存优化参数
        if [ -f ${fi_update_work}/conf/fi_8_0_2_1_script_config_1wuser_2kap_over3point.json ]
        then
            change_one_paras "script_file_name" "fi_8_0_2_1_script_config_1wuser_2kap_over3point.json"
            echo y | cp ${fi_update_work}/conf/fi_8_0_2_1_script_config_1wuser_2kap_over3point.json $odae_work/ODAEDeployTool/etc/datamodel
            return 0
        fi
    fi

}

change_one_paras()
{
    key=$1
    value=$2
    cat $odae_work/ODAEDeployTool/etc/datamodel/FI_u2000.json | grep "$key" > /dev/null
    if [ $? -eq 0 ]
    then
        perl -i -lpe "s~\"$key\".*~\"$key\":\"$value\",~g" $odae_work/ODAEDeployTool/etc/datamodel/FI_u2000.json
    else
        start_line=`sed -n /cluster_file_name/= $odae_work/ODAEDeployTool/etc/datamodel/FI_u2000.json`
        sed -i "$(($start_line-1))a \"$key\":\"$value\"," $odae_work/ODAEDeployTool/etc/datamodel/FI_u2000.json
    fi
}

function update_oms()
{
    set_oms_config
    
    cd  ${odae_work}/ODAEDeployTool/bin
    expect <<END
        spawn bash upgrade_modify_fi_oms_conf.sh
        expect "*assword:"
        send "true,$admin_pwd\r"
        set timeout -1
        expect "fi manager node ip:"
        send "$mainOms\r"
        expect "*assword:"
        send "true,$root_pwd\r"
        set timeout -1
        expect eof

        catch wait ret
        set exit_status [lindex \$ret 3]
        exit \$exit_status
END

}

function update_cluster()
{

    cd $odae_work/ODAEDeployTool/bin/
    
    expect <<END
    spawn bash upgrade_fi.sh postprocess
    set timeout -1
    expect "*assword:"
    send "true,$root_pwd\r"
    set timeout -1
    expect "*assword:"
    send "true,$admin_pwd\r"
    set timeout -1
    expect eof

    catch wait ret
    set exit_status [lindex \$ret 3]
    exit \$exit_status
END
   
    if [ $? -ne 0 ] 
    then
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] run odae postprocess script failed,please check $odae_work/ODAEDeployTool/var/logs"
        log_error "${LINENO}" "run odae postprocess script failed,please check $odae_work/ODAEDeployTool/var/logs"
        return 1
    fi

    shield_alarm
    if [ $? -ne 0 ] 
    then
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] shield_alarm failed"
        log_error "${LINENO}" "shield_alarm failed"
        return 1
    fi
    
    update_oms
    if [ $? -ne 0 ] 
    then
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] Modify OMS configuration failed."
        log_error "${LINENO}" "Modify OMS configuration failed."
        return 1
    fi
    
    return 0
           
}

function unset_parameters()
{
    unset admin_pwd
	unset root_pwd
}

function set_timeout()
{
    if [ -f "/etc/bashrc" ]
    then
        echo "[`date '+%Y-%m-%d %H:%M:%S'`] start to check sys tmout"
        log_info "${LINENO}" "start to check sys tmout"
        tmresult=`cat /etc/bashrc|grep TMOUT`
        if [ ! -n "$tmresult" ]
        then
            echo "[`date '+%Y-%m-%d %H:%M:%S'`] sys tmout not need to change"
            log_info "${LINENO}" "sys tmout not need to change"
            return 0
        fi
        cat /etc/bashrc |grep TMOUT |while read tmout_sys
        do
            if [ ! -n "$tmout_sys" ]
            then
                echo "[`date '+%Y-%m-%d %H:%M:%S'`] sys tmout not need to change"
                log_info "${LINENO}" "sys tmout not need to change"
            else
                echo "[`date '+%Y-%m-%d %H:%M:%S'`] sys tmout need to change" 
                log_info "${LINENO}" "sys tmout need to change"
                if [[ "$tmout_sys" =~ "export" ]]
                then
                    sed -i "s/$tmout_sys/export TMOUT=300/g" /etc/bashrc
                    source /etc/bashrc
                    echo "[`date '+%Y-%m-%d %H:%M:%S'`] sys tmout change success,is to set $TMOUT" 
                    log_info "${LINENO}" "sys tmout change success,is to set $TMOUT"
                else
                    sed -i "s/$tmout_sys/TMOUT=300/g" /etc/bashrc
                    source /etc/bashrc
                    echo "[`date '+%Y-%m-%d %H:%M:%S'`] sys tmout change success,is to set $TMOUT" 
                    log_info "${LINENO}" "sys tmout change success,is to set $TMOUT"
                fi
            fi
        done
    fi
    service sshd restart
    return 0

}

function Main()
{
    log_info "${LINENO}" "update cluster work for update fi to 8.0.2.1"    
    set_premeters
    set_configfile
    update_cluster
    if [ $? -ne 0 ]
    then
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] update cluster work failed"
        log_error "${LINENO}" "update cluster work failed"
        return 1
    fi
    
    echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] update cluster stage work success"
    log_info "${LINENO}" "update cluster stage work success"
 
    
    return 0    
}

get_cur_path
cd "${work_curPath}"

init_log || return $?

Main
mainresult=$?
unset_parameters
exit $mainresult
