#!/bin/bash

source /OSM/script/os_load_base.sh

FLAG=0
SH_NAME=$(basename $0)
function loopRun()
{
    local counter=0
    while [ $counter -le 5 ]
    do
        ((counter++))
        if [ $counter -gt 3 ];then
            sleep 1
        fi
        
        "$@"
        local cmdRet=$?
        [ ${cmdRet} -eq 0 ] && return 0
        OS_echo "[$SH_NAME] error=${cmdRet}, Failed to run: $*." 
    done

    return 1
}
function PATCH_START()
{
    return 
}
function PATCH_END()
{
    local SSH_ALG_CONF=/startup_disk/conf/conf_local/sshalg.conf
    local SSHD_CONFIG=/etc/ssh/sshd_config
    local SSH_ALG_KEX=""
    local SSH_ALG_MAC=""
    local SSH_ALG_CIP=""
	
    chmod 550 /OSM/script/om_chgsshalglevel.sh
    chmod 550 /OSM/script/om_show_omm_info.sh
	
    # recover ssh alg from disk if sshalg.conf exist
    if [ -f $SSH_ALG_CONF ]; then
        SSH_ALG_KEX=`cat $SSH_ALG_CONF | grep -E "^KexAlgorithms"`
        SSH_ALG_MAC=`cat $SSH_ALG_CONF | grep -E "^MACs"`
        SSH_ALG_CIP=`cat $SSH_ALG_CONF | grep -E "^Ciphers"`

        if [ -n "$SSH_ALG_KEX" ]; then
            loopRun sed -i "/^KexAlgorithms/c $SSH_ALG_KEX" $SSHD_CONFIG
        fi

        if [ -n "$SSH_ALG_MAC" ]; then
            loopRun sed -i "/^MACs/c $SSH_ALG_MAC" $SSHD_CONFIG
        fi

        if [ -n "$SSH_ALG_CIP" ]; then
            loopRun sed -i "/^Ciphers/c $SSH_ALG_CIP" $SSHD_CONFIG
        fi

    # save current ssh alg to sshalg.conf
    else
        SSH_ALG_KEX=`cat $SSHD_CONFIG | grep -E "^KexAlgorithms"`
        SSH_ALG_MAC=`cat $SSHD_CONFIG | grep -E "^MACs"`
        SSH_ALG_CIP=`cat $SSHD_CONFIG | grep -E "^Ciphers"`

        loopRun echo "$SSH_ALG_KEX" > $SSH_ALG_CONF
        loopRun echo "$SSH_ALG_MAC" >> $SSH_ALG_CONF
        loopRun echo "$SSH_ALG_CIP" >> $SSH_ALG_CONF
    fi

    return
}

function PATCH_ROLLSTART()
{
    return
}

function PATCH_ROLLEND()
{
    loopRun rm -rf /startup_disk/conf/conf_local/sshalg.conf
    return
}

#start：打补丁前需要执行的操作，脚本的执行时间点在替换文件前
#end：打补丁后需要执行的操作，脚本的执行时间点在替换文件后
#rollstart：回滚补丁时需要执行的操作，脚本的执行时间点在文件被恢复之前。
#rollend：回滚补丁时需要执行的操作，脚本的执行时间点在文件被恢复之后。
#PATCH_CLOSE_SWITCH:先读取性能统计开关的状态，将其值保存到switch中,并关闭性能统计开关
#PATCH_OPEN_SWITCH:如果用户之前是打开状态，将其开关打开
OS_echo "[$SH_NAME] $GProcess: command is ($1)."
L_CMD=$1
case $L_CMD in
    "start") 
        PATCH_START
        ;;
    "end") 
        PATCH_END
        ;;
    "rollstart") 
        PATCH_ROLLSTART
        ;;
    "rollend") 
        PATCH_ROLLEND
        ;;
    *)
        OS_echo "[$SH_NAME] unsupported option."
esac
exit 0

