#!/bin/bash
#
#	This shell script takes care of starting and stopping
#	the KeyServer process (ks).
#
# chkconfig: 345 96 32
# description: KeyServer software management server.
# processname: ks

shopt -s expand_aliases

if [ -e /etc/init.d/functions ] ; then

. /etc/init.d/functions
alias log_success_msg=issue_success
alias log_failure_msg=issue_failure

elif [ -e /lib/lsb/init-functions ] ; then

. /lib/lsb/init-functions
alias status=handle_status

else

alias log_success_msg=echo
alias log_failure_msg=echo
alias status=handle_status

fi

function issue_success ()
{
	action "$1" /bin/true
}

function issue_failure ()
{
	action "$1" /bin/false
}

function handle_status ()
{
	echo $"$1 status unknown"
}

prog="KeyServer"

function start() {
	cd /usr/local/k2
	/usr/local/k2/ks -d
	ret=$?
	if [ $ret -eq 0 ]; then
		log_success_msg $"Starting $prog: "
	else
		log_failure_msg $"Starting $prog: "
	fi
	[ $ret -eq 0 ] && touch /var/lock/subsys/ks
	return $ret
}

function stop() {
	ret=0
	pid=`pidof -s /usr/local/k2/ks`
	if [ "$pid" != "" ] ; then
		for (( i = 0; i < 30; i++ )); do
			if [ ! -d "/proc/$pid" ]; then
				break
			fi
			kill -TERM $pid >/dev/null 2>&1
			ret=$?
			sleep 1
		done
		if [ -d "/proc/$pid" ]; then
			kill -9 $pid >/dev/null 2>&1
			ret=$?
		fi
	fi

	if [ $ret -eq 0 ]; then
		log_success_msg $"Stopping $prog: "
	else
		log_failure_msg $"Stopping $prog: "
	fi
	[ $ret -eq 0 ] && rm -f /var/lock/subsys/ks
	return $ret
}

function restart() {
	stop
	sleep 1
	start
}

function condrestart() {
	[ -e /var/lock/subsys/ks ] && restart || :
}

# See how we were called.
case "$1" in
  start)
	start
	;;
  stop)
	stop
	;;
  status)
	status ks
	;;
  restart)
	restart
	;;
  condrestart)
	condrestart
	;;
  *)
	echo $"Usage: $0 {start|stop|status|condrestart|restart}"
	exit 1
esac

exit $?

