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

# Do not load RH compatibility interface.
WITHOUT_RC_COMPAT=1

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

RETVAL=0

PGUSER=postgres
CONFIG="/etc/pgbouncer.ini"
PIDFILE="/var/run/pgbouncer/pgbouncer.pid"
BINARY="/usr/bin/pgbouncer"
OPTIONS="-d /etc/pgbouncer.ini"

start()
{
	if [ -f "$PIDFILE" ]; then
		failure "$PIDFILE exists. Probably another instance of pgbouncer is running ?..."
	else
		if  
		start_daemon --user "$PGUSER"  --expect-user root --displayname pgbouncer -- "$BINARY" "$OPTIONS"
        RETVAL=$?
        return $RETVAL
		
		then
			echo_success
		else
			echo_failure
		fi
	fi
	
}

stop()
{

	stop_daemon --pidfile "$PIDFILE" --expect-user "$PGUSER" --displayname pgbouncer -- "$BINARY" 
	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 pgbouncer
		RETVAL=$?
		;;
	*)
	echo "Usage: ${0##*/} {start|stop|restart|status}"
		RETVAL=1
esac

exit $RETVAL
