#! /bin/sh
### BEGIN INIT INFO
# Provides:          mongrel-cluster
# Required-Start:    $remote_fs $syslog
# Required-Stop:$remote_fs $syslog
# Should-Start:      $network
# Should-Stop:       $network
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start mongrel servers at boot time
### END INIT INFO
#
# Copyright (c) 2007 Bradley Taylor, bradley@railsmachine.com
#
# mongrel_cluster       Startup script for Mongrel clusters.
#
# chkconfig: - 85 15
# description: mongrel_cluster manages multiple Mongrel processes for use \
#              behind a load balancer.
#
# Debianized by Filipe Lautert, filipe@icewall.org

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/sbin/mongrel_cluster_ctl
NAME=mongrel-cluster
DESC=mongrel-cluster

test -x $DAEMON || exit 0

CONF_DIR=/etc/mongrel-cluster/sites-enabled
PID_DIR=/var/run/mongrel-cluster
DAEMON_OPTS="-c $CONF_DIR"

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

set -e

# if we do not hae configuration files, skip the script
TOTAL_CONFS=$(ls $CONF_DIR | wc -l)
test $TOTAL_CONFS -ne 0 || exit 0

# Add user and group information, if specified
if [ -n "$USER" ]; then DAEMON_OPTS="$DAEMON_OPTS --user $USER"; fi
if [ -n "$GROUP" ]; then DAEMON_OPTS="$DAEMON_OPTS --group $GROUP"; fi

warn_unhandled_conf() {
	if IGNORED_CONF=$(ls $CONF_DIR | grep -v '\.conf$\|\.yml$')
	then
	    echo '** Warning: Ignoring configuration files with extensions'
	    echo '   other than .conf and .yml:'
	    echo "   $IGNORED_CONF"
	fi
}

case "$1" in
  start)
	mkdir -p $PID_DIR
        chown $USER:$GROUP $PID_DIR
	echo -n "Starting $DESC: "
	start-stop-daemon --start --quiet \
		--exec $DAEMON -- start $DAEMON_OPTS
	echo "$NAME."
	warn_unhandled_conf
	;;
  stop)
	echo -n "Stopping $DESC: "
	start-stop-daemon --start --quiet \
		--exec $DAEMON -- stop $DAEMON_OPTS
	echo "$NAME."
	;;
  restart)
	echo -n "Restarting $DESC: "
	start-stop-daemon --start --quiet \
		--exec $DAEMON -- restart $DAEMON_OPTS
	echo "$NAME."
	warn_unhandled_conf
	;;
  status)
	echo -n "Status for $DESC: "
	start-stop-daemon --start --quiet \
		--exec $DAEMON -- status $DAEMON_OPTS
	;;
  # actually just calls restart
  force-reload)
	echo -n "Restarting $DESC: "
	start-stop-daemon --start --quiet --chuid $USER:$GROUP \
		--exec $DAEMON -- restart $DAEMON_OPTS
	echo "$NAME."
	warn_unhandled_conf
	;;
  *)
	N=/etc/init.d/$NAME
	echo "Usage: $N {start|stop|restart|status}" >&2
	exit 1
	;;
esac

exit 0
