#! /bin/bash

declare product_dir='/opt/fiupdate/NCE_info'
declare work_path="/opt/fiupdate"

echo -n "es_input: os_pwd_root"
read -s os_pwd_root

echo ""

echo -n "es_input: os_pwd_ossadm"
read -s os_pwd_ossadm

echo ""

echo -n "es_input: fi_pwd_admin"
read -s fi_pwd_admin

GetWorkPath()
{
    echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] Precheck work is start."
    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
    return 0
}

InputParas()
{
    whouser=`whoami`
    if [ "$whouser" != "root" ]
    then
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] please run this script as user 'root' "
        exit 1
    fi
    
    root_pwd=${os_pwd_root}
    ossadm_pwd=${os_pwd_ossadm}
    admin_pwd=${fi_pwd_admin}
    
    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}")
}

Lock()
{
    cd /opt/fiupdate
    expect <<END
    spawn bash safelock.sh
    expect {
        "please input root password:" {send "$root_pwd\r"}
    }
    set timeout -1
    expect "*#"
    exit
END
}

ClearAlarm()
{
    cd /opt/fiupdate/py_work
    script="clear_alarm.pyc"
    if [ -f clear_alarm.py ]
    then
        script="clear_alarm.py"
    fi
    webip=`cat /opt/fiupdate/NCE_info/nodes_*.ini |grep fiweb | sed  's/fiweb=//g'`
    
    expect <<END
        spawn /opt/fiupdate/ODAESwiftDeployPlugin/ODAEDeployTool/rtsp/python/bin/python $script $webip 14003,12034
        set timeout 60
        exec sleep 10
        expect {
            "*assword*" {send "$admin_pwd\r"}
            timeout {send_user "No response!\n"
                    exit 1}
        }
        set timeout 1800
        expect eof
        catch wait ret
        set exit_status [lindex \$ret 3]
        exit \$exit_status
END
    return 0
}

CheckAlarm()
{
    cd /opt/fiupdate/py_work
    script="check_alarm.pyc"
    if [ -f check_alarm.py ]
    then
        script="check_alarm.py"
    fi
    webip=`cat /opt/fiupdate/NCE_info/nodes_*.ini |grep fiweb | sed  's/fiweb=//g'`

    expect <<END
        spawn /opt/fiupdate/ODAESwiftDeployPlugin/ODAEDeployTool/rtsp/python/bin/python $script $webip
        set timeout 60
        exec sleep 10
        expect {
            "*assword*" {send "$admin_pwd\r"}
            timeout {send_user "No response!\n"
                    exit 1}
        }
        set timeout 1800
        expect eof
        catch wait ret
        set exit_status [lindex \$ret 3]
        exit \$exit_status
END
    if [ $? -ne 0 ]
    then
        echo "FI is abnormal, please check web."
        return 1
    else
        echo "FI is normal."
    fi
    return 0
}

CheckService()
{
    cd /opt/fiupdate/py_work
    script="check_service.pyc"
    if [ -f check_service.py ]
    then
        script="check_service.py"
    fi
    webip=`cat /opt/fiupdate/NCE_info/nodes_*.ini |grep fiweb | sed  's/fiweb=//g'`

    expect <<END
        spawn /opt/fiupdate/ODAESwiftDeployPlugin/ODAEDeployTool/rtsp/python/bin/python $script $webip
        set timeout 60
        exec sleep 10
        expect {
            "*assword*" {send "$admin_pwd\r"}
            timeout {send_user "No response!\n"
                    exit 1}
        }
        set timeout 1800
        expect eof
        catch wait ret
        set exit_status [lindex \$ret 3]
        exit \$exit_status
END
    if [ $? -ne 0 ]
    then
        echo "FI is abnormal, please check FI web."
        return 1
    else
        echo "FI is normal."
    fi
    return 0
}

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'`
    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'`
    
    if [ "$mode" == "double" ]
    then
        backupOms=`cat /opt/fiupdate/NCE_info/nodes_${product_name}.ini |grep backupOms= |sed 's/backupOms=//g'`
    fi
    return 0
     
}

do_password_age()
{
    fi_access_ip=$1
    cd ${work_path}/py_work
    check_pwd_utilpy=${work_path}/py_work/check_pwd_util.pyc
    if [ -f ${work_path}/py_work/check_pwd_util.py ]
    then
        check_pwd_utilpy=${work_path}/py_work/check_pwd_util.py
    fi
    pythonCmd=${work_path}/ODAESwiftDeployPlugin/ODAEDeployTool/rtsp/python/bin/python

    expect <<END
        spawn su ossadm -c "${pythonCmd} ${check_pwd_utilpy} $fi_access_ip"
        expect {
        "*assword*" {send "$admin_pwd\r"}
        }
        set timeout 120
        expect eof
END

}

check_password_age()
{
    echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] start to check admin password age"
    echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] start to check admin password age" >> ${curpath}/log/update_fi_pre_alarm_service.log
    cd /opt
    do_password_age $1 > ${work_path}/log/CheckPd.log

    if [ ! -f "${work_path}/log/CheckPd.log" ]
    then
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] test passwd log file not exists,can not check passwd age"
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] test passwd log file not exists,can not check passwd age" >> ${curpath}/log/update_fi_pre_alarm_service.log
        return 1
    fi
    
    admin_result=`cat ${work_path}/log/CheckPd.log|grep "Pwd will Expired days"`
    if [ -n "${admin_result}" ]
    then
        ages=`echo ${admin_result} | awk -F "days" {'print $2'} | sed s/[[:space:]]//g`
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] The password will expire in ${ages} days, please change the password in time."
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] The password will expire in ${ages} days, please change the password in time." >> ${curpath}/log/update_fi_pre_alarm_service.log
        echo -e "The login password for FusionInsight Manager will expire in ${ages} days, please change the password immediately." > ${curpath}/log/check_pwd_age.log
        return 1
    fi
    admin_result=`cat ${work_path}/log/CheckPd.log|grep "password is expired"`
    if [ -n "${admin_result}" ]
    then
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] The password has expired, please change the password immediately."
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] The password has expired, please change the password immediately." >> ${curpath}/log/update_fi_pre_alarm_service.log
        echo -e "The login password for FusionInsight Manager has expired, please change the password immediately." > ${curpath}/log/check_pwd_age.log
        echo -e "And then modify parameters by referring to steps 2 and 3 in section 'FAQs'->'What Do I Do If the Login Password for FusionInsight Manager Expires?' in the 'Upgrade Guide'." >> ${curpath}/log/check_pwd_age.log
        return 1
    fi
    echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] FI web admin password age is normal."
    echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] FI web admin password age is normal." >> ${curpath}/log/update_fi_pre_alarm_service.log

    if [ -f "/tmp/CheckPd.log" ]
    then
        rm -f /tmp/CheckPd.log
    fi
    return 0
}

pdAdmin()
{
    cfg_file=$1
    fi_access_ip=$2
    cd ${work_path}/py_work
    check_region1pwdpy=${work_path}/py_work/check_region1pwd.pyc
    if [ -f ${work_path}/py_work/check_region1pwd.py ]
    then
        check_region1pwdpy=${work_path}/py_work/check_region1pwd.py
    fi
    pythonCmd=${work_path}/ODAESwiftDeployPlugin/ODAEDeployTool/rtsp/python/bin/python

    expect <<END
        spawn su ossadm -c "${pythonCmd} ${check_region1pwdpy} $cfg_file $fi_access_ip"
        expect {
        "*assword*" {send "$ossadm_pwd\r"}
        }
        set timeout 120
        expect eof
END

}

testAdmin()
{
    echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] start to check FI web admin password"
    echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] start to check FI web admin password" >> ${curpath}/log/update_fi_pre_alarm_service.log
    cd /opt
    pdAdmin $1 $2 > ${work_path}/log/TestPd.log

    if [ ! -f "${work_path}/log/TestPd.log" ]
    then
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] test passwd log file not exists,can not check passwd is right or not"
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] test passwd log file not exists,can not check passwd is right or not" >> ${curpath}/log/update_fi_pre_alarm_service.log
        return 1
    fi
    
    admin_result=`cat ${work_path}/log/TestPd.log|grep "Test to login FI success,password is right"`
    if [ -z "${admin_result}" ]
    then
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] FI web admin password is wrong ,please enter the right password"
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] FI web admin password is wrong ,please enter the right password" >> ${curpath}/log/update_fi_pre_alarm_service.log
        return 1
    fi
    echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] FI web admin password is right"
    echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] FI web admin password is right" >> ${curpath}/log/update_fi_pre_alarm_service.log

    if [ -f "/tmp/TestPd.log" ]
    then
        rm -f /tmp/TestPd.log
    fi
    return 0
}

SetIptables()
{
    SysVerInfo=`cat /etc/*-release`
    if [[ "$SysVerInfo" =~ "SLES" ]]; then
        echo "[`date '+%Y-%m-%d %H:%M:%S'`] system is SUSE." 
        omp01_eth0_ip=`ifconfig eth0 | grep "inet " | awk '{print $2}'` | awk -F: '{print $2}'
        omp01_eth1_ip=`ifconfig eth1 | grep "inet " | awk '{print $2}'` | awk -F: '{print $2}'
        omp01_eth3_ip=`ifconfig eth3 | grep "inet " | awk '{print $2}'` | awk -F: '{print $2}'
        SysVer="SUSE"
    elif [[ "$SysVerInfo" =~ "EulerOS" ]]; then
        echo "[`date '+%Y-%m-%d %H:%M:%S'`] system is EulerOS."
        omp01_eth0_ip=`ifconfig eth0 | grep "inet " | awk '{print $2}'`
        omp01_eth1_ip=`ifconfig eth1 | grep "inet " | awk '{print $2}'`
        omp01_eth3_ip=`ifconfig eth3 | grep "inet " | awk '{print $2}'`
        SysVer="EulerOS"
    else
        echo "[`date '+%Y-%m-%d %H:%M:%S'`] system is not SUSE,is not EulerOS."
        return 0
    fi
    
    eth0_web_ip=`cat /opt/fiupdate/NCE_info/nodes_*.ini | grep fiweb | awk -F'=' '{print $2}'`
    
    # if fi web in iptables, skip iptables config
    setiptables=`iptables -t nat -nL | grep ${eth0_web_ip} | grep 28443`
    if [ "x${setiptables}" = "x" ] && [ "x${omp01_eth1_ip}" = "x" ]
    then
        iptables -t nat -A PREROUTING -d ${omp01_eth3_ip} -p tcp --dport 28443 -jDNAT --to-dest ${eth0_web_ip}:28443
        iptables -t nat -A POSTROUTING -d ${eth0_web_ip} -p tcp --dport 28443 -jSNAT --to-source ${omp01_eth0_ip}
        
        iptables -t nat -A PREROUTING -d ${omp01_eth3_ip} -p tcp --dport 20009 -jDNAT --to-dest ${eth0_web_ip}:20009
        iptables -t nat -A POSTROUTING -d ${eth0_web_ip} -p tcp --dport 20009 -jSNAT --to-source ${omp01_eth0_ip}
        
        iptables -t nat -A PREROUTING -d ${omp01_eth3_ip} -p tcp --dport 20026 -jDNAT --to-dest ${eth0_web_ip}:20026
        iptables -t nat -A POSTROUTING -d ${eth0_web_ip} -p tcp --dport 20026 -jSNAT --to-source ${omp01_eth0_ip}
        
        iptables -t nat -A PREROUTING -d ${omp01_eth3_ip} -p tcp --dport 20044 -jDNAT --to-dest ${eth0_web_ip}:20044
        iptables -t nat -A POSTROUTING -d ${eth0_web_ip} -p tcp --dport 20044 -jSNAT --to-source ${omp01_eth0_ip}
        
        # save in /etc/sysconfig/iptables
        service iptables save
    fi
    
}

Main()
{
    InputParas
    SetIptables
    Lock
    lockResult=`cat ${curpath}/log/lock_safe.log | grep "script in stage lock all FI nodes success"`
    if [ "x${lockResult}" == "x" ]
    then
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] \033[41;30m Safe lock is failed. \033[0m"
        return 1
    else
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] \033[42;34m Safe lock is success. \033[0m"
    fi
    is_alarm_ok=0
    is_service_ok=0
    is_region1pwd_ok=0
    is_pwdage_ok=0
    ClearAlarm
    sleep 20
    CheckAlarm
    if [ $? -ne 0 ]
    then
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] FI alarm is abnormal, please check web."
        echo "Waring: The number of alarms exceeds 1, please check."
        is_alarm_ok=1
    else
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] FI alarm is normal."
    fi
    
    CheckService
    if [ $? -ne 0 ]
    then
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] FI service is abnormal, please check FI web."
        is_service_ok=1
    else
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] FI service is normal."
    fi
    chown -R ossadm:ossgroup ${curpath}
    product_all=`find $product_dir/ -name "node*.ini" -type f`
    for product_ini in ${product_all}
    do
    {
        product_one=$(basename $product_ini .ini|sed 's/nodes_//g')
        cfg_file="/opt/fiupdate/NCE_info/product_${product_one}.json"
        echo "get config json file:[${cfg_file}]..."
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] Start to do $product_one product"
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] Start to do $product_one product" >> ${curpath}/log/update_fi_pre_alarm_service.log
        set_premeters $product_one
        if [ $? -ne 0 ]
        then
            echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] $product_one: postwork set parameters failed"
            echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] $product_one: postwork set parameters failed" >> ${curpath}/log/update_fi_pre_alarm_service.log
            return 1
        fi
        check_password_age ${fiweb}
        if [ $? -ne 0 ]
        then
            echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] \033[41;37m ${product_one} The admin password age is abnormal. Please check and correct it.\033[0m"
            echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] \033[41;37m ${product_one} The admin password age is abnorma. Please check and correct it.\033[0m" >> ${curpath}/log/update_fi_pre_alarm_service.log
            is_pwdage_ok=1
        fi
        testAdmin ${cfg_file} ${fiweb}
        if [ $? -ne 0 ]
        then
            echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] \033[41;37m ${product_one} The region1-pwd configuration on the $product_one 31945 page is incorrect. Please check and correct it.\033[0m"
            echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] \033[41;37m ${product_one} The region1-pwd configuration on the $product_one 31945 page is incorrect. Please check and correct it.\033[0m" >> ${curpath}/log/update_fi_pre_alarm_service.log
            is_region1pwd_ok=1
        fi
    }
    done
    if [ $is_alarm_ok -eq 1 -o $is_service_ok -eq 1 -o $is_region1pwd_ok -eq 1 -o $is_pwdage_ok -eq 1 ];then
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] \033[42;34m Precheck work is failed. \033[0m"
        return 1
    fi
    echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] \033[42;34m Precheck work is successfully. \033[0m"
    return 0

}

SuperMain()
{
    Main $* > ${curpath}/log/update_fi_pre_alarm_service.log
    ret=$?
    if [ $ret -eq 0 ]
    then
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] Precheck work in stage Checkalarmservice is successfully."
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] Precheck work in stage Checkalarmservice is successfully." >> ${curpath}/log/update_fi_pre_alarm_service.log
    else
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] Precheck work in stage Checkalarmservice is failed."
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] Precheck work in stage Checkalarmservice is failed." >> ${curpath}/log/update_fi_pre_alarm_service.log
    fi
    chown -R ossadm:ossgroup ${curpath}/log/
}

GetWorkPath
SuperMain $* &
superret=$?
exit $superret
