#! /bin/sh

set -e

PATH=/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/sbin/pgpool
NAME=pgpool
DESC='PostgreSQL collection pool daemon'
PIDFILE=/var/run/postgresql/pgpool.pid

test -x $DAEMON || exit 0

# Include pgpool defaults if available
if [ -f /etc/default/pgpool ] ; then
	. /etc/default/pgpool
fi

OPTS=""
if [ x"$PGPOOL_LOG_DEBUG" = x"yes" ]; then
	OPTS="$OPTS -d"
fi


is_running()
{
	if [ ! -f "$PIDFILE" ]; then
		return 1
	fi

	pid=`cat "$PIDFILE"`

	if kill -0 "$pid" 2>/dev/null; then
		:
	else
		return 1
	fi

	if [ ! -e /proc/"$pid"/exe ]; then
		return 1
	fi

	if [ `readlink /proc/"$pid"/exe` != "$DAEMON" ]; then
		return 1
	fi

	return 0
}


case "$1" in
  start)
	echo -n "Starting $DESC: $NAME"
	if is_running; then
		:
	else
		su - postgres "$DAEMON -n $OPTS 2>&1 </dev/null | logger -t pgpool -p ${PGPOOL_SYSLOG_FACILITY:-local0}.info >/dev/null 2>&1 &"
	fi
	echo "."
	;;
  stop)
	echo -n "Stopping $DESC: $NAME"
	start-stop-daemon --stop --quiet --oknodo --pidfile $PIDFILE --signal INT --retry INT/20/QUIT/10/KILL/10 --exec $DAEMON
	echo "."
	;;
  restart|force-reload)
	$0 stop
	sleep 1
	$0 start
	;;
  *)
	N=/etc/init.d/$NAME
	echo "Usage: $N {start|stop|restart|force-reload}" >&2
	exit 1
	;;
esac

exit 0
