#! /bin/bash

#进程数组
proc_arr=("PNSDHCPSvr" "PNSTFTPSvr" "PNSVDiskSvr" "pns_p2ps")
default_path="/opt/apps/com.jumple.pns.server/files/jumple/pns"

#后面考虑增加读配置文件
proc_path=$default_path    
#proc_path="."

#service cfg file
configFile=$proc_path/"cfg/service.ini"

shellFile=$0


#read ini file  
function ReadINIfile()  
{   
	Key=$1
	Section=$2
  	Configfile=$3
	ReadINI=`awk -F '=' '/\['$Section'\]/{a=1}a==1&&$1~/'$Key'/{print $2;exit}' $Configfile`  
 	#echo "$ReadINI" 
    #return $ReadINI
    value=$(echo $ReadINI | sed -e 's/\r//g')

    echo $value
} 
 
#return 0-success, 1-already exited，暂时不考虑程序执行失败的问题
start(){
    echo "--start $1--"

    exec_file=$1

    #judge is exit   若果脚本有参数，grep时需要提出脚本本身运行的程序
    #eg:./PNSWatchdog.sh --start PNSVDiskSvr, grep时就需要剔除这个程序
    # msg=`ps -ef | grep "$exec_file" | grep -v "grep" |grep -v "$shellFile"`
    # echo "msg:$msg"

    count=`ps -ef | grep "$exec_file" | grep -v "grep" |grep -v "$shellFile" |wc -l`
    echo "count:$count"
    if [ 0 == $count ];then   
        ($proc_path/$exec_file)  1>/dev/null 2>&1 &      #启动指定程序
    else 
        echo "$exec_file already existed."
        return 1
    fi

    echo "start End"

    return 0
}
 
#return 0-success, 1-not exited 
stop(){
    echo "--stop $1--"
    pid=$(ps -ef|grep  $1 |grep -v grep | grep -v "$shellFile" |awk '{print $2}')
    #echo "($pid)"
    if [ -z $pid ]; then   #如果进程不存在，则pid为空（pid为字符串）
        echo "service is not exit ..."
        return 1
    else
        kill -9 $pid  1>/dev/null 2>&1
    fi  

    return 0
}
 
checkrun(){ 
    while true
    do
        for var in ${proc_arr[@]};
        do
            #read service ini
            dhcp=`ReadINIfile "dhcp" "service" "$configFile"`
            sys=`ReadINIfile "sys" "service" "$configFile"`

            #echo "dhcp:$dhcp."
            echo "[$dhcp]"
            echo "[$sys]"

            #judge is exit
            count=`ps -ef | grep $var | grep -v "grep" |wc -l`
            echo $count
            if [ 0 == $count ];then 
                if [ "PNSDHCPSvr" = "$var" ]; then   #judge dhcp
                    if [ "1" = "$dhcp" ]; then  
                        echo "$var not exit, restart the proc"
                        ($proc_path/$var) 1>/dev/null 2>&1 &      #启动指定程序
                    else 
                        echo "dhcp flag is 0"
                    fi
                else  #judge sys
                    if [ "1" = "$sys" ]; then  
                        echo "$var not exit, restart the proc"
                        ($proc_path/$var) 1>/dev/null 2>&1 &      #启动指定程序
                    fi
                fi
            fi
        done

        sleep 1s
    done
} 
 
case $1 in
--start):
    start $2
    ;;
--stop):
    stop  $2
    ;;
--checkrun):
    checkrun
    ;;
*):
    echo "error ..."
    ;;
esac

echo "shell over"






