#!/bin/sh
### BEGIN INIT INFO
# Provides:          schooltool
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: SchoolTool server
### END INIT INFO

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/bin/supervisord
CONTROL=/usr/bin/supervisorctl
NAME=schooltool
DESC="SchoolTool"

INSTANCE=standard
CONFIGFILE=/etc/schooltool/$INSTANCE/supervisord.conf
DAEMON_OPTS="-c $CONFIGFILE"
PIDFILE=/var/run/schooltool/supervisord.pid
DODTIME=5                   # Time to wait for the server to die, in seconds
                            # If this value is set too low you might not
                            # let some servers to die gracefully and
                            # 'restart' will not work

# Gracefully exit if the package has been removed or is not configured.
test -f $CONFIGFILE || exit 0
test -x $DAEMON || exit 0

. /lib/lsb/init-functions

running () {
    pidofproc -p $PIDFILE $DAEMON >/dev/null
    return $?
}

case "$1" in
  start)
	# Make sure we have a /var/run sub-directory
        [ -d /var/run/schooltool ] \
            || install --group schooltool --owner schooltool -d /var/run/schooltool

	log_begin_msg "Starting $DESC..."
	if running ; then
	    [ -n "$DODTIME" ] && sleep $DODTIME
	    $CONTROL $DAEMON_OPTS start all >/dev/null || true
	fi
	start-stop-daemon --start --quiet --oknodo --pidfile $PIDFILE \
	    --startas $DAEMON -- $DAEMON_OPTS --user schooltool
	log_end_msg $?
	;;
  stop)
	log_begin_msg "Stopping $DESC..."
	if running ; then
	    $CONTROL $DAEMON_OPTS shutdown >/dev/null
	fi
	start-stop-daemon --stop --quiet --oknodo --pidfile $PIDFILE
	log_end_msg $?
	;;
  restart|force-reload)
	# Make sure we have a /var/run sub-directory
        [ -d /var/run/schooltool ] \
            || install --group schooltool --owner schooltool -d /var/run/schooltool

	log_begin_msg "Restarting $DESC..."
	if running ; then
	    $CONTROL $DAEMON_OPTS shutdown >/dev/null
	fi
	start-stop-daemon --stop --quiet --oknodo --pidfile $PIDFILE
	[ -n "$DODTIME" ] && sleep $DODTIME
	start-stop-daemon --start --quiet --pidfile $PIDFILE \
	    --startas $DAEMON -- $DAEMON_OPTS --user schooltool
	log_end_msg $?
	;;
  status)
	if [ ! -f "$PIDFILE" ] ; then
		echo "SchoolTool is not running."
		exit 1
	fi
	/usr/bin/supervisorctl $DAEMON_OPTS status
	exit 0
	;;
  *)
	SCRIPTNAME=/etc/init.d/$NAME
	log_success_msg "Usage: $SCRIPTNAME {start|stop|restart|force-reload|status}" \
                >&2
        exit 1
	;;
esac

exit 0
