#!/bin/bash

source /OSM/script/os_load_base.sh
SH_NAME=$(basename $0)

function PATCH_START()
{
	return 
}
function PATCH_END()
{
	OS_echo "[$SH_NAME] start"
	chmod 640 /OSM/conf/MO/eam_mo_memory.json
	#判定该进程是否已经被加载，是否还在运行
    red=`pidof cfg_app`
    OS_echo "[$SH_NAME] cfg_app old pid: $red"
    if [ "$red" = "" ]; then
		OS_echo "[$SH_NAME] cfg_app is not running"
        #进程不在位，直接返回OK
        return
    fi
	#to kill cfg_app
	kill -9 `pidof cfg_app` 
	OS_echo "kill cfg_app end"
	#检查进程kill后是否正常拉起
	rednew=`pidof cfg_app`
    RETRY_TIMES=0
    while [ -z "$rednew" -a $RETRY_TIMES -lt 10 ] || [ $red -eq $rednew -a $RETRY_TIMES -lt 10 ]
    do
        ((RETRY_TIMES++))
        OS_echo "[$SH_NAME] Check cfg_app status, times($RETRY_TIMES)."
        sleep 0.2
        rednew=`pidof cfg_app`
    done
	OS_echo "[$SH_NAME] cfg_app new pid: $rednew"
	if [ "$rednew" = "" ] || [ $red -eq $rednew ]; then
        OS_echo "[$SH_NAME] $GProcess old pid is $red, new pid is $rednew."
    fi
	return
}

function PATCH_ROLLSTART()
{
	return
}

function PATCH_ROLLEND()
{
	OS_echo "[$SH_NAME] rollback"
	chmod 640 /OSM/conf/MO/eam_mo_memory.json
	#判定该进程是否已经被加载，是否还在运行
    red=`pidof cfg_app`
    OS_echo "[$SH_NAME] cfg_app oldPid: $red"
    if [ "$red" = "" ]; then
		OS_echo "[$SH_NAME] cfg_app is not running"
        #进程不在位，直接返回OK
        return
    fi
	# to kill cfg_app
	kill -9 `pidof cfg_app`
	OS_echo "kill cfg_app end"
	#检查进程kill后是否正常拉起
	rednew=`pidof cfg_app`
    RETRY_TIMES=0
    while [ -z "$rednew" -a $RETRY_TIMES -lt 10 ] || [ $red -eq $rednew -a $RETRY_TIMES -lt 10 ]
    do
        ((RETRY_TIMES++))
        OS_echo "[$SH_NAME] Check cfg_app status, times($RETRY_TIMES)."
        sleep 0.2
        rednew=`pidof cfg_app`
    done
	OS_echo "[$SH_NAME] cfg_app rollback pid: $rednew"
	if [ "$rednew" = "" ] || [ $red -eq $rednew ]; then
        OS_echo "[$SH_NAME] $GProcess old pid is $red, new pid is $rednew."
    fi
	return
}
#start：打补丁前需要执行的操作，脚本的执行时间点在替换文件前
#end：打补丁后需要执行的操作，脚本的执行时间点在替换文件后
#rollstart：回滚补丁时需要执行的操作，脚本的执行时间点在文件被恢复之前。
#rollend：回滚补丁时需要执行的操作，脚本的执行时间点在文件被恢复之后。
#PATCH_CLOSE_SWITCH:先读取性能统计开关的状态，将其值保存到switch中,并关闭性能统计开关
#PATCH_OPEN_SWITCH:如果用户之前是打开状态，将其开关打开
OS_echo "[$SH_NAME] 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