#! /bin/sh
#
### BEGIN INIT INFO
# Provides:          zarafa-server
# Required-Start:    $syslog $network $remote_fs
# Required-Stop:     $syslog $network $remote_fs
# Should-Start:      mysql
# Should-Stop:       mysql
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Zarafa Collaboration Platform's Storage Server
# Description:       The Zarafa Server takes MAPI calls in SOAP over HTTP(S) or
#                    the unix socket. It authenticates users using one of three
#                    authentication backends (unix/pam, db, ldap). It stores the data
#                    in a MySQL instance, and optionally stores the attachments directly
#                    on the filesystem.
### END INIT INFO

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
SERVER=/usr/bin/zarafa-server
DESC="Zarafa server"
NAME=`basename $SERVER`
#QUIETDAEMON=--quiet
PIDFILE=/var/run/$NAME.pid

test -x $SERVER || exit 0

# Include zarafa defaults if available
if [ -f /etc/default/zarafa ] ; then
	. /etc/default/zarafa
	export ZARAFA_USERSCRIPT_LOCALE
fi
if [ -z "$ZARAFA_LOCALE" ]; then
	ZARAFA_LOCALE="C"
fi

if [ -e "$SERVER_CONFIG" ]; then
	SERVER_OPTS="$SERVER_OPTS -c $SERVER_CONFIG"
fi

#set -e

. /lib/lsb/init-functions

case "$1" in
  start)
	if [ "$SERVER_ENABLED" = "no" ]; then
		log_warning_msg "Zarafa Server daemon not enabled in /etc/default/zarafa ... not starting"
		exit 0
	fi
	log_begin_msg "Starting $DESC: $NAME"
	export LC_ALL=$ZARAFA_LOCALE
	export LANG=$ZARAFA_LOCALE
	start-stop-daemon --start $QUIETDAEMON --pidfile $PIDFILE --exec $SERVER -- $SERVER_OPTS
	log_end_msg $?
	unset LC_ALL LANG
	;;
  stop)
	if [ -f /tmp/zarafa-upgrade-lock ]; then
		echo
		echo "Zarafa database upgrade is taking place."
		echo "Do not stop this process bacause it may render your database unusable."
		echo
		exit 1
	fi
	# the server may take up to 60 seconds to exit, so we wait a bit longer than that
	log_begin_msg "Stopping $DESC: $NAME"
	start-stop-daemon --stop $QUIETDAEMON --pidfile $PIDFILE --retry TERM/65 --exec $SERVER
	RETVAL=$?
	rm -f $PIDFILE
	log_end_msg $RETVAL
	;;
  restart)
	$0 stop
	$0 start
	;;
  status)
	status_of_proc "$SERVER" "$NAME" && exit 0 || exit $?
	;;
  reload|force-reload)
	log_begin_msg "Reloading $DESC: $NAME"
	start-stop-daemon --stop $QUIETDAEMON --signal HUP --pidfile $PIDFILE --exec $SERVER
	log_end_msg $?
	;;
  *)
	N=/etc/init.d/$NAME
	echo "Usage: $N {start|stop|restart|reload|force-reload|status}" >&2
	exit 1
	;;
esac

exit 0
