#!/bin/sh
#
# pgpool	This is the init script for starting up pgpool
#
# chkconfig:	345 85 15
# description:	Pgpool - a connection pooling/replication server for PostgreSQL
# processname:	pgpool
# pidfile:	/var/run/pgpool/pgpool.pid
# config:	/etc/pgpool.conf

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

# Get network config
. /etc/sysconfig/network

PGPOOL_BIN=/usr/bin/pgpool
PGPOOLUID=pgpool
PGPOOLGID=pgpool
PGPOOLCONF=/etc/pgpool.conf
PGPOOLHBA=/etc/pool_hba.conf
SHUTDOWN_MODE=smart

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

# 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 pgpool
		exit 1
	fi
else
	exit 0
fi


start() {
	# Check if the service is already running?
	if [ ! -f /var/lock/subsys/pgpool ]; then
		msg_starting pgpool
		busy
		start-stop-daemon -S -x $PGPOOL_BIN -c $PGPOOLUID:$PGPOOLGID -p /var/run/pgpool/pgpool.pid \
			-- -f $PGPOOLCONF -a $PGPOOLHBA $OPTS
		RETVAL=$?
		if [ $RETVAL -eq 0 ]; then
			touch /var/lock/subsys/pgpool
			ok
		else
			fail
		fi
	else
		msg_already_running pgpool
	fi
}


stop() {
	# Stop daemons.
	if [ -f /var/lock/subsys/pgpool ]; then
		msg_stopping pgpool
		busy
		output=$($PGPOOL_BIN -f "$PGPOOLCONF" -m "$SHUTDOWN_MODE" stop 2>&1)
		if [ $? -eq 0 ]; then
			rm -f /var/run/pgpool/pgpool.pid >/dev/null 2>&1
			ok
		else
			fail
			echo $output >&2
			killproc -p /var/run/pgpool/pgpool.pid pgpool >/dev/null
			rm -f /var/run/pgpool/pgpool.pid >/dev/null 2>&1
		fi
		rm -f /var/lock/subsys/pgpool
	else
		msg_not_running pgpool
	fi
}

reload() {
	if [ -f /var/lock/subsys/pgpool ]; then
		msg_reloading pgpool
		busy
		$PGPOOL_BIN -f $PGPOOLCONF reload
		if [ $? -eq 0 ]; then
			ok
		else
			fail
		fi
	else
		msg_not_running pgpool
	fi
}

RETVAL=0
# See how we were called.
case "$1" in
  start)
	start
	;;
  stop)
	stop
	;;
  status)
	status pgpool
	RETVAL=$?
	;;
  restart)
	stop
	start
	;;
  reload|force-reload)
	reload
	;;
  *)
	msg_usage "$0 {start|stop|restart|reload|force-reload|status}"
	exit 3
	;;
esac

exit $RETVAL
