#! /bin/sh
#
# calendarserver startup script
#
### BEGIN INIT INFO
# Provides:          caldavserver
# Required-Start:    $network
# Required-Stop:     $network
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: CalDAV Calendarserver
### END INIT INFO

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/bin/caldavd
NAME=caldavd
DESC=calendarserver
RUNDIR=/var/run/caldavd/
SPOOLDIR=/var/spool/caldavd/

test -x $DAEMON || exit 0

# Include calendarserver defaults if available
if [ -f /etc/default/calendarserver ] ; then
	. /etc/default/calendarserver
fi

. /lib/lsb/init-functions

set -e

check_start_daemon() {
  if [ ! "$start_calendarserver" = "yes" ]; then
    log_warning_msg "Not starting calendarserver, disabled via /etc/default/calendarserver"
    return 1
  else
    return 0
  fi
}

case "$1" in
  start)
  	if check_start_daemon; then
	    log_daemon_msg "Starting $DESC" "$NAME"
	    mkdir -p $RUNDIR
	    chown --reference=$SPOOLDIR $RUNDIR
	    if start-stop-daemon --start --quiet --pidfile $RUNDIR$NAME.pid \
		    --exec $DAEMON -- $DAEMON_OPTS 2>/dev/null; then
	        log_end_msg 0
	        RET=0
	    else
	        log_end_msg 1
	        RET=1
	    fi
	fi
	;;
  stop)
	log_daemon_msg "Stopping $DESC" "$NAME"
	if start-stop-daemon --oknodo --stop --quiet --pidfile $RUNDIR$NAME.pid \
		--exec /usr/bin/python; then
	    log_end_msg 0
	    RET=0
	else
	    log_end_msg 1
	    RET=1
	fi
	;;
  restart|force-reload)
	#
	#	If the "reload" option is implemented, move the "force-reload"
	#	option to the "reload" entry above. If not, "force-reload" is
	#	just the same as "restart".
	#
  	if check_start_daemon; then
	    log_daemon_msg "Restarting $DESC" "$NAME"
	    start-stop-daemon --stop --quiet --oknodo  --pidfile \
		    $RUNDIR$NAME.pid --exec /usr/bin/python
	    sleep 1
	    if start-stop-daemon --start --quiet --pidfile \
		    $RUNDIR$NAME.pid --exec $DAEMON -- $DAEMON_OPTS 2>/dev/null; then
	        log_end_msg 0
	        RET=0
	    else
	        log_end_msg 1
	        RET=1
	    fi
	fi
	;;
  *)
	N=/etc/init.d/$NAME
	# echo "Usage: $N {start|stop|restart|reload|force-reload}" >&2
	echo "Usage: $N {start|stop|restart|force-reload}" >&2
	exit 1
	;;
esac

exit $RET
