#!/bin/sh
#
# mongrel_cluster	Startup script for Mongrel clusters.
#
# chkconfig: - 84 16
# description:	mongrel_cluster manages multiple Mongrel processes for use \
#		behind a load balancer.
# processname: ruby
# config: /etc/sysconfig/mongrel_cluster

# Do not load RH compatibility interface.
WITHOUT_RC_COMPAT=1

# Source function library.
. /etc/init.d/functions

CONFDIR=/etc/mongrel_cluster/sites-enabled
PIDDIR=/var/run/mongrel_cluster
LOGDIR=/var/log/mongrel_cluster
LOCKFILE=/var/lock/subsys/mongrel_cluster
CLUSTER_CTL=/usr/bin/mongrel_cluster_ctl
RETVAL=0

cfgs="$(find "$CONFDIR" -maxdepth 1 -mindepth 1 -name '*.yml' -o -name '*.conf')"
[ -n "$cfgs" ] ||
	exit 0

[ -d "$PIDDIR" ] ||
	mkdir -p "$PIDDIR"
chown root:root "$PIDDIR"
chmod 1777 "$PIDDIR"

cluster_command()
{
	local cmd
	cmd="$1" && shift

	"$CLUSTER_CTL" "$cmd" -c "$CONFDIR" --pid_file "$PIDDIR/mongrel.pid" --log_file "$LOGDIR/mongrel.log" --user _mongrel --group _mongrel "$@"
}

start()
{
	cluster_command start --clean
	RETVAL=$?
	[ $RETVAL -eq 0 ] && touch "$LOCKFILE"
	return $RETVAL
}

stop()
{
	cluster_command stop
	RETVAL=$?
	[ $RETVAL -eq 0 ] && rm -f "$LOCKFILE"
	return $RETVAL
}

restart()
{
	cluster_command restart --clean
	RETVAL=$?
	return $RETVAL
}

# See how we were called.
case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	restart|reload)
		restart
		;;
	condstop)
		if [ -e "$LOCKFILE" ]; then
			stop
		fi
		;;
	condrestart|condreload)
		if [ -e "$LOCKFILE" ]; then
			restart
		fi
		;;
	status)
		cluster_command status
		RETVAL=$?
		;;
	*)
		msg_usage "${0##*/} {start|stop|reload|restart|condstop|condrestart|condreload|status}"
		RETVAL=1
esac

exit $RETVAL
