#!/bin/bash
#
### BEGIN INIT INFO
# Provides:          bicsuite-zope4
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Should-Start:      $network $named $time
# Should-Stop:       $network $named $time
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start and stop the bicsuite Enterprise Job Scheduling web gui
# Description:       Controls the bicsuite web gui zope4 server
### END INIT INFO
#
. /opt/bicsuite/etc/SETTINGS
set -e
set -u

if [ -f /lib/lsb/init-functions ]; then
	. /lib/lsb/init-functions
	LOG_WARNING_MSG=log_warning_msg
	LOG_FAILURE_MSG=log_failure_msg
	ECHO_SUCCESS=echo
	ECHO_FAILURE=echo
else
	LOG_WARNING_MSG=echo
	LOG_FAILURE_MSG=echo
	ECHO_SUCCESS=echo
	ECHO_FAILURE=echo
fi


SELF=$(cd $(dirname $0); pwd -P)/$(basename $0)

# Safeguard (relative paths, core dumps..)
cd /
umask 077

case "${1:-''}" in
  'start')
	echo -n "Starting bicsuite Enterprise Job Scheduling webserver"
	[ -p /opt/bicsuite/log/zope4.out ] || su bicsuite -c "mkfifo /opt/bicsuite/log/zope4.out"
	su - bicsuite /bin/bash -c ". /opt/bicsuite/.bashrc; scrolllog /opt/bicsuite/log/zope4.out -e /opt/bicsuite/Zope4/bin/runwsgi -v /opt/bicsuite/bicsuiteweb4/etc/zope.ini" >/dev/null 2>&1
	$ECHO_SUCCESS
	;;

  'stop')
	echo -n "Stopping bicsuite Enterprise Job Scheduling webserver"
	su - bicsuite /bin/bash -c ". /opt/bicsuite/.bashrc; fuser -k -INT /opt/bicsuite/log/zope4.out" >/dev/null 2>&1
	$ECHO_SUCCESS
	;;

  'restart')
	echo -n "Restarting bicsuite Enterprise Job Scheduling webserver"
	[ -p /opt/bicsuite/log/zope4.out ] || su bicsuite -c "mkfifo /opt/bicsuite/log/zope4.out"
	su - bicsuite /bin/bash -c ". /opt/bicsuite/.bashrc; fuser -k -INT /opt/bicsuite/log/zope4.out" >/dev/null 2>&1
	su - bicsuite /bin/bash -c ". /opt/bicsuite/.bashrc; scrolllog /opt/bicsuite/log/zope4.out -e /opt/bicsuite/Zope4/bin/runwsgi -v /opt/bicsuite/bicsuiteweb4/etc/zope.ini" >/dev/null 2>&1
	$ECHO_SUCCESS
	;;

  'reload'|'force-reload')
  	$LOG_WARNING_MSG "Reloading bicsuite!web not supported; use 'restart' instead"
	log_end_msg 0
	;;

  'status')
	if fuser -s /opt/bicsuite/log/zope4.out 2>/dev/null
	then
	  echo "bicsuite!web4 is up"
	else
	  echo "bicsuite!web4 is down"
	  exit 3
	fi
  	;;

  *)
	echo "Usage: $SELF start|stop|restart|reload|force-reload|status"
	exit 1
	;;
esac
