#!/bin/sh
# SRCE generic init script
# Copyright (C) 2007 Tim Post - All Rights Reserved
# chkconfig: 2345 98 01

# description: Starts and stops SRCED auth and exec daemons.

### BEGIN INIT INFO
# Provides:          srced
# Required-Start:     
# Should-Start:
# Required-Stop:      
# Should-Stop:
# Default-Start:     3 4 5
# Default-Stop:      0 1 2 6
# Default-Enabled:   yes
# Short-Description: Start/stop srced
# Description:       Starts and stops srced/srce-execd
### END INIT INFO

die()
{
	echo $*
	exit 1
}

# sanity checking
. /etc/srced/srced.ini || die "/etc/srced/srced.ini not found."
[ -e ${PREFIX}/sbin/srced ] || die "${PREFIX}/sbin/srced not found!"
[ -e /etc/srced/srced.conf ] || die "srced.conf could not be found!"

if [ -f /etc/init.d/functions ]; then
	. /etc/init.d/functions
else
	success() {
		printf "[ OK ]"
	}
	failure() {
		printf "[ FAILED ]"
	}
fi

RETVAL=0
PROGNAME=$(basename $0)
PROCESSNAME="srced"
PIDFILE="/var/run/srced.pid"
RESTARTPAUSE=2

case "$1" in
  start)
        if [ -f "$PIDFILE" ] && [ ! -z $(cat $PIDFILE) ]; then
                pid=$(cat $PIDFILE)
                echo "$PROGNAME is already running, $PIDFILE reports PID # $pid"
                exit 1
        fi
        printf "Starting %s:\t\t\t\t" "$PROGNAME"
        ${PREFIX}/sbin/srced
        RETVAL="$?"
        if [ "$RETVAL" = 0 ]; then
                success
        else
                failure
        fi
		echo
        ;;
  stop)
        if [ ! -f "$PIDFILE" ] || [ -z $(cat $PIDFILE) ]; then
                echo "$PROGNAME is not running, $PIDFILE does not exist, or no valid pid was found."
                echo "Try $0 force-reload instead."
                echo
                exit 1
        fi
        printf "Stopping %s:\t\t\t\t" "$PROGNAME"
        ${PREFIX}/sbin/srced -t > /dev/null
        RETVAL="$?"
        if [ "$RETVAL" = 0 ]; then
                success
        else
                failure
        fi
		echo
        ;;
  restart)
        $0 stop
        sleep $RESTARTPAUSE
        $0 start
        ;;
  reload)
        $0 restart
        ;;
  force-reload)
        echo "Forcing killall of $PROGNAME (sig 9) ... "
        killall -9 $PROGNAME > /dev/null 2>&1
        $0 restart
        ;;
  status)
        if [ -f "$PIDFILE" ]; then
                pid=$(cat $PIDFILE)
                echo "$PROGNAME is running, PID # $pid"
                RETVAL=0
        else
                echo "$PROGNAME is not running. ($PIDFILE not found)"
                RETVAL=1
        fi
        ;;
  *)
        echo "Usage: $PROGNAME {start|stop|restart|reload|force-reload|status}"
        RETVAL=1
esac
exit $RETVAL

