#!/bin/bash

source /OSM/script/os_load_base.sh

#制作补丁时，修改GProcess和Cgroup和GoldProcess即可.
#GProcess：替换的进程全路径名称 Cgroup：该进程所属的Cgroup组名

GProcess=/OSM/bin/alarm
Cgroup=ommother

SH_NAME=$(basename $0)
PROCESS_NAME="$1"

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 restartAlmProcess()
{
    #判定该进程是否已经被加载，是否还在运行
    red=$(ps -ww -eo pid,cmd | grep $GProcess | grep -v grep | awk '{print $1}')
    OS_echo "[$SH_NAME] $GProcess oldPid: $red"
    if [ "$red" = "" ]; then
        #进程不在位，只有demon不在位的情况，同时如果不在位资源利用率也不会太高，此处不考虑，直接返回OK
        return 0
    fi
	
    OS_echo "[$SH_NAME] $GProcess will be killed."
	
	loopRun daemon -s $GProcess
	
    loopRun daemon $GProcess "/OSM/bin/cgroup_manage.sh -g $Cgroup"
    
    rednew=$(ps -ww -eo pid,cmd | grep $GProcess | grep -v grep | awk '{print $1}')
    local RETRY_TIMES=0
    while [ -z "$rednew" -a $RETRY_TIMES -lt 5 ] || [ $red -eq $rednew -a $RETRY_TIMES -lt 10 ]
    do
        ((RETRY_TIMES++))
        OS_echo "[$SH_NAME] Check $GProcess status, times($RETRY_TIMES)."
        sleep 0.2
        rednew=$(ps -ww -eo pid,cmd | grep $GProcess | grep -v grep | awk '{print $1}')
    done
    
    OS_echo "[$SH_NAME] newPid: $rednew"
    if [ "$rednew" = "" ] || [ $red -eq $rednew ]; then
        OS_echo "[$SH_NAME] $GProcess old pid is $red, new pid is $rednew."
    fi

    return 0
}

function restartIbaseProcess()
{
	OS_echo "[$SH_NAME] $PROCESS_NAME will be killed."

	ps -ef |grep -E "ibase|httpd"|grep -v grep |awk '{print $2}'|xargs kill -9
	
	if [ $? -ne 0 ]; then
		ps -ef |grep -E "ibase|httpd"|grep -v grep |awk '{print $2}'|xargs kill -9
		
		OS_echo "[$SH_NAME] $PROCESS_NAME is killed again $?."
	fi
	
    return 0
}

function restartSnmpProcess()
{
	OS_echo "[$SH_NAME] $PROCESS_NAME will be killed."

	kill -9 `pidof snmpagent`
	
	if [ $? -ne 0 ]; then
		kill -9 `pidof snmpagent`
		OS_echo "[$SH_NAME] $PROCESS_NAME is killed again $?."
	fi
	
    return 0
}

PROCESS_NAME="$1"

if [ "$PROCESS_NAME" == "alarm" ]; then
	restartAlmProcess
	exit $?
fi

if [ "$PROCESS_NAME" == "ibase" ]; then
	restartIbaseProcess
	exit $?
fi

if [ "$PROCESS_NAME" == "snmp" ]; then
	restartSnmpProcess
	exit $?
fi

OS_echo "[$SH_NAME] It is not support the process: $PROCESS_NAME."
exit 1

