#!/bin/sh
#
# pound
#
# chkconfig:	345 85 15
# description:	reverse-proxy and load-balancer
#

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

# Get network config
. /etc/sysconfig/network

# List of instances to start.
POUND_INSTANCES="pound"

# Get service config
[ -f /etc/sysconfig/pound ] && . /etc/sysconfig/pound

# Check that networking is up.
if is_yes "${NETWORKING}"; then
	if [ ! -f /var/lock/subsys/network -a "$1" != stop -a "$1" != status ]; then
		msg_network_down pound
		exit 1
	fi
else
	exit 0
fi

# check if the $1 instance is up
is_up() {
	local instance="$1"
	local pidfile=/var/run/pound/$instance.pid
	[ -f $pidfile ] || return 1
	local pid=$(cat $pidfile)
	kill -0 $pid 2>/dev/null
	return $?
}

start() {
	local ret started=0
	# Check if the service is already running?
	if [ ! -f /var/lock/subsys/pound -o "$single" = 1 ]; then
		for instance in $POUND_INSTANCES; do
			is_up $instance && continue
			msg_starting "Pound ($instance)"
			PIDFILE=/var/run/pound/$instance.pid
			start-stop-daemon --start \
			--exec /usr/sbin/pound \
			--pidfile $PIDFILE -- -v -f /etc/pound/$instance.cfg -p $PIDFILE
			ret=$?
			if [ $ret -eq 0 ]; then
				ok
			   	RETVAL=$ret
				started=1
			else
				failed
			fi
		done
		[ $started = 1 ] && touch /var/lock/subsys/pound

		if [ -z "$ret" -a "$single" = 1 ]; then
			msg_already_running "Pound ($instance)"
		fi
	else
		msg_already_running "Pound"
	fi
}

stop() {
	local ret
	# Stop daemons.
	if [ -f /var/lock/subsys/pound ]; then
		for instance in $POUND_INSTANCES; do
			is_up $instance || continue
			msg_stopping "Pound ($instance)"
			killproc --pidfile pound/$instance.pid pound
			ret=$?
		done
		[ "$single" != 1 ] && rm -f /var/lock/subsys/pound > /dev/null 2>&1
		if [ -z "$ret" -a "$single" = 1 ]; then
			msg_not_running "Pound ($instance)"
		fi
	else
		msg_not_running "Pound"
	fi
}

restart() {
	if [ "$single" != 1 ]; then
		# make up list of configured and up instances
		local list
		for instance in $POUND_INSTANCES; do
			is_up $instance || continue
			list="$list $instance"
		done
		POUND_INSTANCES=$list
	fi

	stop
	start
}

if [ "$1" != status -a "$2" ]; then
	POUND_INSTANCES="$2"
	single=1
fi

RETVAL=0
# See how we were called.
case "$1" in
  start)
  	start
	;;
  stop)
  	stop
	;;
  status)
	nls "Configured Pound instances:"
   	echo " $POUND_INSTANCES"
	nls "Currently active Pound instances:"
	stat=1
	for pidfile in /var/run/pound/*.pid; do
		[ -f "$pidfile" ] || continue
		instance=${pidfile#/var/run/pound/}
		instance=${instance%.pid}
		is_up $instance && echo -n " $instance($(cat $pidfile))"
		stat=0
	done
	echo ""
	exit $stat
	;;
  restart|force-reload)
	restart
	;;
  *)
	msg_usage "$0 {start|stop|restart|force-reload|status} [INSTANCE NAMES]"
	exit 3
esac

exit $RETVAL
