#!/bin/sh
#
# Multiplatform init script
# etersafe - loads the etersafe
#
# chkconfig: 345 70 60
# description:  etersafe - program keylock
#               
# modulename: etersafe
# processnames: etersafe
#

SERVNAME=etersafed
OUTFORMAT=/etc/init.d/outformat
[ -x $OUTFORMAT ] || OUTFORMAT=/etc/init.d/etersafe.outformat
if which tput >/dev/null && test -x $OUTFORMAT ; then
	. $OUTFORMAT
else
	MOVE_TO_COL(){ :; }
	SETCOLOR_SUCCESS(){ :; }
	SETCOLOR_FAILURE(){ :; }
	SETCOLOR_WARNING(){ :; }
	SETCOLOR_NORMAL(){ :; }
fi


# TODO: use printf?
success()
{
	MOVE_TO_COL
	echo -n '[ '
	SETCOLOR_SUCCESS
	echo -n 'DONE'
	SETCOLOR_NORMAL
	echo ' ]'
}

failure()
{
	MOVE_TO_COL
	echo -n '['
	SETCOLOR_FAILURE
	echo -n 'FAILED'
	SETCOLOR_NORMAL
	echo ']'
}

passed()
{
	MOVE_TO_COL
	echo -n '['
	SETCOLOR_WARNING
	echo -n 'PASSED'
	SETCOLOR_NORMAL
	echo ']'
}

get_pid()
{
	# TODO: use pgrep
	PIDOF=/bin/pidof
	if [ -x $PIDOF ] ; then
		dpid=`$PIDOF $1`
	else
		dpid="$(ps axh | grep $1 | grep -v grep | sed -e 's/ *\(.*\)/\1/' -e 's/ \+/ /g' | grep -v " /bin/sh " | grep -v "^$$ " |  cut -f1 -d\  | head -1)"
	fi
	test -n "$dpid"
}

is_loaded()
{
    get_pid $1
    test -n "$dpid"
}

start()
{
    echo -n "Running $SERVNAME... "
    is_loaded $SERVNAME && passed && return
# TODO: use full path
    $SERVNAME && success || { failure ; exit 1 ; }
}

stopping()
{
	is_loaded $1 || { passed ; return ; }
	kill -KILL $dpid
	for pau in 1 2 3 4 5 6 7 ; do
		is_loaded $1 || { success ; return ; }
		echo -n "."
		# 0.5 do not work only on Special Linux
		sleep 1
	done
	failure
}

stop()
{
    for i in $SERVNAME ; do
        echo -n "Stopping $i... "
	stopping $i
    done

}

status()
{
	echo "$SERVNAME status:"
	for i in $SERVNAME ; do
		if is_loaded $i ; then
			echo "    $i is running"
			echo -n "Test connection to..."
			etersafetest >/dev/null && success || failure
		else
			echo "    $i is stopped"
		fi
	done
}

restart()
{
    stop
    start
}

case "$1" in
    start)
        start
        ;;
    condstop|stop)
        stop
        ;;
    restart)
        restart
        ;;
    status)
        status
        ;;
    condrestart)
        # only restart if it is already running
	is_loaded $SERVNAME && restart
        ;;
    *)
        echo "Usage: etersafe {start|stop|restart|condrestart|condstop|status}"
esac

