#! /bin/sh
#
# /etc/init.d/slon
#
# slon		This is the init script for starting up the slony1
#               daemon
# chkconfig: -  86 2345
# description: 	Starts and stops the slony1 daemon that handles all database requests.
#
# processname: slon
# pidfile: /var/run/slon.pid
#

# Do not load RH compatibility interface.
WITHOUT_RC_COMPAT=1

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

RETVAL=0

PGUSER=postgres
CFGS=$(/bin/ls -1 /etc/slony1.d/*)
CFGS="${CFGS//\/etc\/slony1.d\//}"

buildenv()
{
	CONFIG="/etc/slony1.d/$1"
	PIDFILE="${CONFIG%.conf}.pid"
	PIDFILE="/var/run/slony1/${PIDFILE#/etc/slony1.d/}"
	LOCKFILE="${CONFIG/.conf/}"
	LOCKFILE="/var/lock/subsys/${LOCKFILE#/etc/slony1.d/}"
}
										

noargs_start()
{
	for CONFIG in $CFGS ; do
		buildenv $CONFIG
	if [ -f "$PIDFILE" ]; then
		failure "$PIDFILE exists. Probably another instance of slon is running ?..."
	else
		msg_starting slon
		if /bin/su -l "$PGUSER" -s /bin/sh -c "/usr/bin/slon -f \"$CONFIG\" -p \"$PIDFILE\" &> /dev/null &" ; then
			echo_success
		else
			echo_failure
		fi
	fi
	done
}

noargs_stop()
{
	for CONFIG in $CFGS ; do
		buildenv $CONFIG
	if [ -f "$PIDFILE" ]; then
		stop_daemon --pidfile "$PIDFILE" --lockfile "$LOCKFILE" --expect-user "$PGUSER" -- /usr/bin/slon
	fi
	done
}
		
start()
{
	if [ $# -eq 0 ]; then
		noargs_start		
	else
		buildenv $1
	if [ -f "$PIDFILE" ]; then
		failure "$PIDFILE exists. Probably another instance of slon is running ?..."
	else
		msg_starting slon
		if /bin/su -l "$PGUSER" -s /bin/sh -c "/usr/bin/slon -f \"$CONFIG\" -p \"$PIDFILE\" &> /dev/null &" ; then
			echo_success
		else
			echo_failure
		fi
	fi
	fi
	echo
	RETVAL=$?
	return $RETVAL
}

stop()
{
	if [ $# -eq 0 ]; then
		noargs_stop
	else
		buildenv $1
	if [ -f "$PIDFILE" ]; then
		stop_daemon --pidfile "$PIDFILE" --lockfile "$LOCKFILE" --expect-user "$PGUSER" -- /usr/bin/slon
	fi
	fi
	RETVAL=$?
	return $RETVAL
}

restart()
{
	stop $1
	start $1
}

case "$1" in 
	start)
		shift
		start "$@" 
		;;
	stop)
		shift
		stop "$@"
		;;
	restart )
		shift
		restart "$@"
		;;
	status )
		status --expect-user postgres slon
		RETVAL=$?
		;;
	*)
	echo "Usage: ${0##*/} {start|stop|restart|status config_file_name (i.e. replica.conf)}"
		RETVAL=1
esac

exit $RETVAL
