#!/bin/sh
### BEGIN INIT INFO
# Provides:          Qi An Xin Technology Group Inc.
# Required-Start:
# Required-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Endpoint Security Protection
# Description:       Qi An Xin Endpoint Protection Platforms
### END INIT INFO

INSTALLDIR="/opt/apps/com.qianxin.qaxsafe/files"
INSTALLCONF="/opt/.installpath.conf"
if [ ! -d "$INSTALLDIR" ]; then
	if [ -d "${INSTALLCONF}" ]; then
		INSTALLDIR="`cat /opt/.installpath.conf`/qaxsafe"
	else
		INSTALLDIR="/opt/qaxsafe"
	fi
fi
NAME="qaxsafed"
FULLPATH="$INSTALLDIR/$NAME"
PIDNAME="$INSTALLDIR/.qaxsafed.pid"
PPIDNAME="$INSTALLDIR/.qaxsafed.ppid"

if [ -e "/lib/lsb/init-functions" ]; then
	. /lib/lsb/init-functions
fi

check_alive_pid()
{
	if [ ! -f "$1" ]; then
		return 0
	fi
	pid=`cat $1 2>/dev/null`
	if [ ! -f "$1" ]; then
		return 0
	fi
	ret1=`ps -CPc 2>/dev/null | grep "^$pid" | grep "$NAME" | wc -l`
	ret2=`ps --no-headers -p $pid 2>/dev/null | grep "$NAME" | wc -l`
	ret=`expr $ret1 + $ret2`
	if [ $ret -eq 1 ]; then
		return 1
	else
		return 0
	fi
}

query_process_status()
{
	check_alive_pid $2 && check_alive_pid $3
	if [ $? -eq 0 ];then
		echo "stopped    $1 "
		return 1
	else
		echo "running    $1"
		return 0
	fi
}

status()
{
	echo "=================status===================="
	query_process_status $FULLPATH $PIDNAME $PPIDNAME
	return $?
}

loop_query_start()
{
	query_times=10
	while [ $query_times -gt 0 ]; do
		check_alive_pid $2
		if [ $? -eq 1 ];then
			query_times=0
		else
			echo "waiting start $1 ..."
			query_times=`expr $query_times - 1`
			sleep 1
		fi
	done

	check_alive_pid $2
	if [ $? -eq 0 ]; then
		echo "start $1 failed."
	fi
}

loop_query_stop()
{
	query_times=10
	while [ $query_times -gt 0 ]; do
		check_alive_pid $2
		if [ $? -eq 1 ];then
			echo "waiting stop $1 ..."
			query_times=`expr $query_times - 1`
			sleep 1
		else
			query_times=0
		fi
	done
}

start_process()
{
	check_alive_pid $2
	if [ $? -eq 0 ]; then
		`nohup $1 >/dev/null 2>&1 &`
		loop_query_start $1 $2
	else
		echo "$1 is already started"
	fi
}

stop_process()
{
	check_alive_pid $2
	if [ $? -eq 1 ]; then
		pid=`cat $2 2>/dev/null`
		ppid=`cat $3 2>/dev/null`
		echo "try to stop monitor process $ppid..."
		echo "try to stop main process $pid..."
		echo "..."
		kill -KILL $ppid
		kill -KILL $pid
		loop_query_stop $1 $2
	else
		echo "$1 is already stopped"
	fi
}

start()
{
	echo "=================start====================="
	echo "..."

	start_process $FULLPATH $PIDNAME

	status
	return $?
}

stop()
{
	echo "==================stop====================="
	echo "..."

	stop_process $FULLPATH $PIDNAME $PPIDNAME

	status
	if [ $? -eq 0 ];then
		return 1
	else
		return 0
	fi
}

case "$1" in
	start)
		start && exit 0 || exit $?
		;;
	stop)
		stop && exit 0 || exit $?
		;;
	status)
		status && exit 0 || exit $?
		;;
	*)
		echo "Usage : $0 {start|status}"
		exit 1
esac

exit 0
