#! /bin/sh
#
# Ejudge is a programming contest managment system.
#
# chkconfig: - 90 10
# description: Ejudge daemon - programming contests managment server
#
### BEGIN INIT INFO
# Provides: ejudge
# Required-Start: httpd2
# Required-Stop: httpd2
# Default-Start:  3 4 5
# Default-Stop: 0 1 2 6
# Short-Description: start and stop ejudge service
# Description: Ejudge is a programming contest managment system
### END INIT INFO

# Do not load RH compatibility interface.

WITHOUT_RC_COMPAT=1

. /etc/init.d/functions

SOCKET_DIR=/var/run/ejudge
SUPERSERVE_SOCKET=$SOCKET_DIR/super-serve-socket
USERLIST_SOCKET=$SOCKET_DIR/userlist-socket
NEWSERVER_SOCKET=$SOCKET_DIR/new-server-socket
RETVAL=0

start() {
    test -d $SOCKET_DIR || mkdir $SOCKET_DIR && chown ejudge:judges $SOCKET_DIR
    start_daemon --user ejudge -- ejudge-control -f start
    RETVAL=$?
    return $RETVAL
}

stop() {
    action "Stopping ejudge-control service:" ejudge-control stop
    RETVAL=$?
    return $RETVAL
}

reload() {
    killall -HUP ej-users ej-super-server ej-compile ej-super-run ej-jobs ej-contests
}

case "$1" in
  start)
    start
    ;;
  stop)
    stop
    ;;
  restart)
    stop
    start
    ;;
  reload)
    reload
    ;;
  condstop)
    if [ -e "$SUPERSERVE_SOCKET" ] || [ -e "$USERLIST_SOCKET" ] || [ -e "$NEWSERVER_SOCKET" ] ; then
      stop
    fi
    ;;
  condrestart)
    if [ -e "$SUPERSERVE_SOCKET" ] || [ -e "$USERLIST_SOCKET" ] || [ -e "$NEWSERVER_SOCKET" ] ; then
      stop
      start
    fi
    ;;
  condreload)
    if [ -e "$SUPERSERVE_SOCKET" ] || [ -e "$USERLIST_SOCKET" ] || [ -e "$NEWSERVER_SOCKET" ] ; then
      reload
    fi
    ;;
  status)
    RETVAL=0
    for f in users super-server compile super-run jobs contests
    do
      ps -C ej-$f > /dev/null || { echo "ej-$f process not running" ; RETVAL=1 ; }
    done
    if [[ $RETVAL = 0 ]]
    then
      echo "All ejudge services are running"
    fi
    ;;
  *)
    msg_usage "${0##*/} {start|stop|reload|restart|status|condstop|condreload|condrestart}"
    RETVAL=1
esac

exit $RETVAL

