#! /bin/sh
# Copyright (c) 2007 Novell Inc / SUSE Linux AG, Nuernberg, Germany.
# All rights reserved.
#
# Author: Peter Poeml <poeml@suse.de>
#
### BEGIN INIT INFO
# Provides:                     eddie tool
# Required-Start:               $local_fs $remote_fs $network
# Required-Stop:                $local_fs $remote_fs $network
# Should-Start:                 $named $time 
# Should-Stop:                  $named $time 
# Default-Start:                3 5
# Default-Stop:                 0 1 2 6
# Short-Description:            Eddie Tool
# Description:                  Start the Eddie Tool
### END INIT INFO


: ${EDDIE:=/usr/bin/python /usr/bin/eddie.py}
: ${pidfile:=/var/run/eddie.pid}


. /etc/rc.status
rc_reset

case "$1" in
    start)
        echo -n "Starting service eddie "
	if ! pgrep -u root -f "$EDDIE" >/dev/null; then
		startproc -q -f $EDDIE -d
	else
		echo -n " (already running)"
	fi

        rc_status -v
        ;;
    stop)
        echo -n "Shutting down service eddie "
	#pkill -u root -f "$EDDIE" 

	if ! [ -f $pidfile ]; then
		echo -n "(not running)"
	else
		pid=$(<$pidfile)
		kill -TERM $pid 2>/dev/null
		case $? in
		    1)  echo -n "(not running)";;
		    0)  # wait until the processes are gone (the parent is the last one)
			echo -n "(waiting for it to terminate) "
			for ((wait=0; wait<120; wait++)); do
				if test -f $pidfile; then 
					usleep 500000
					continue
				fi
				if ! test -f /proc/$pid/exe; then
					break
				fi
				case "$(readlink /proc/$pid/exe 2>/dev/null)" in
				*/python*)  usleep 500000;;
				*)          break;;
				esac
			done
			;;
		esac
	fi

	rc_status -v
        ;;
    try-restart)
        ## Do a restart only if the service was active before.
        ## Note: try-restart is now part of LSB (as of 1.9).
        ## RH has a similar command named condrestart.
        $0 status
        if test $? = 0; then
                $0 restart
        else
                rc_reset        # Not running is not a failure.
        fi
        # Remember status and be quiet
        rc_status
        ;;
    restart)
        $0 stop

        for i in 1 2 3 4 5; do
                if $0 status &>/dev/null; then
                        sleep 1
                else
                        continue
                fi
        done

        $0 start
        rc_status
        ;;
    reload|force-reload)
        echo -n "Reload service eddie "
        killproc -HUP $EDDIE 2> /dev/null || true
        rc_status -v
        ;;
    status)
        echo -n "Checking for service eddie: "
	pgrep -u root -f "$EDDIE" >/dev/null
        #checkproc $EDDIE
        rc_status -v
        ;;
    *)
        echo "Usage: $0 {start|stop|status|try-restart|restart|force-reload|reload|probe}"
        exit 1
esac
rc_exit

