#! /bin/sh
#
# skeleton	example file to build /etc/init.d/ scripts.
#		This file should be used to construct scripts for /etc/init.d.
#
#		Written by Miquel van Smoorenburg <miquels@cistron.nl>.
#		Modified for Debian GNU/Linux
#		by Ian Murdock <imurdock@gnu.ai.mit.edu>.
#
# Version:	@(#)skeleton  1.8  03-Mar-1998  miquels@cistron.nl
#
# Caudium init.d startup file
#
### BEGIN INIT INFO
# Provides:          caudium
# Required-Start:    $local_fs $syslog $named $network $time
# Required-Stop:     $local_fs $syslog $named $network
# Should-Start:      
# Should-Stop:       
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: caudium webserver
# Description:       caudium is a webserver
### END INIT INFO

set -e

if ! [ -x "/lib/lsb/init-functions" ]; then
  . /lib/lsb/init-functions
else
  echo "E: /lib/lsb/init-functions not found, lsb-base (>= 3.0-6) needed"
  exit 1
fi


EXTVER=
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON_DIR=/usr/share/caudium${EXTVER}
DAEMON=$DAEMON_DIR/start-caudium
NAME=caudium${EXTVER}
DESC="Caudium Webserver"

PIDFILE=/var/run/caudium${EXTVER}/caudium.pid
DEFSTART_OPTIONS="--pid-file=$PIDFILE --config-dir=/etc/caudium${EXTVER}/servers/ --log-dir=/var/log/caudium${EXTVER}/"

test -f $DAEMON || exit 0

set -e

if test -f /etc/default/caudium${EXTVER}; then
    . /etc/default/caudium${EXTVER}
fi

case "$1" in
  start)
	echo -n "Starting $DESC: "

	if [ -f $PIDFILE ] ; then
	    caudiumPID=`cat $PIDFILE | head -1`
	    caudiumRunning=`ps -ef | grep $caudiumPID | grep -v grep` || true
	fi

	if [ "x${caudiumRunning}" != "x" ] ; then
	    echo "Caudium is already running with pid: ${caudiumPID}"
	else
	    find /var/cache/caudium/cache/ -type f -print ! -user www-data -exec chown www-data:www-data {} \; >/dev/null 2>&1
	    start-stop-daemon --start --pidfile $PIDFILE --quiet --chdir $DAEMON_DIR \
		--exec $DAEMON -- $DEFSTART_OPTIONS $START_OPTIONS > /dev/null
	    echo "$NAME."
	    
	fi
	;;
  stop)
    echo -n "Stopping $DESC: "
    start-stop-daemon --stop --pidfile $PIDFILE --signal 15 --oknodo --retry 10 > /dev/null 2>&1 || true
    echo "$NAME."
	;;
  reload|force-reload)
    start-stop-daemon --stop --pidfile $PIDFILE --signal 1 --oknodo > /dev/null 2>&1 || true
	;;
  restart)
	#
	#	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".
	#
	$0 stop
	sleep 3
	$0 start
	;;
  *)
	N=$0
	# echo "Usage: $N {start|stop|restart|reload|force-reload}" >&2
	echo "Usage: $N {start|stop|restart|force-reload}" >&2
	exit 1
	;;
esac

exit 0
