#!/bin/sh

### BEGIN INIT INFO
# Provides:          pgbouncer
# Required-Start:    $local_fs $remote_fs $network $syslog $named
# Required-Stop:     $local_fs $remote_fs $network $syslog $named
# Should-Start:      postgresql
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: start pgbouncer
# Description: pgbouncer is a connection pool server and replication
#              proxy for PostgreSQL.
### END INIT INFO

PATH=/sbin:/bin:/usr/sbin:/usr/bin
NAME=pgbouncer
DAEMON=/usr/sbin/$NAME
PIDDIR=/var/run/postgresql
PIDFILE=$PIDDIR/$NAME.pid
OPTS="-d /etc/pgbouncer/$NAME.ini"
RUNASUSER="postgres"

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

# Exit if we were uninstalled with the config still there
test -x $DAEMON || exit 0

# Check if configuration exists
test -f $CONF || exit 0

SSD="start-stop-daemon --pidfile $PIDFILE --exec $DAEMON"

case "$1" in
  start)
    # Check if we are still disabled in /etc/default/pgbouncer
    [ "${START:-}" = "0" ] && exit 0
    echo -n "Starting server: $NAME"
    test -d $PIDDIR || install -d -o postgres -g postgres -m 2775 $PIDDIR
    $SSD --start --chuid $RUNASUSER --oknodo -- $OPTS 2> /dev/null
    ;;

  stop)
    echo -n "Stopping server: $NAME"
    $SSD --stop --retry 30 --oknodo
    ;;

  reload | force-reload)
    echo -n "Reloading $NAME configuration"
    $SSD --stop --signal HUP --oknodo
    ;;

  restart)
    $SSD --status
    if [ $? -eq 0 ] ; then
	echo -n "Invoking $NAME restart"
	su -c "$DAEMON -R $OPTS 2> /dev/null" - $RUNASUSER
	sleep 5
	$SSD --status
    else
	$0 start
    fi
    ;;

  status)
    $SSD --status
    status=$?
    if [ $status -eq 0 ]; then
	echo "pgbouncer is running"
    else
	echo "pgbouncer is not running"
    fi
    exit $status
    ;;

  *)
    echo "Usage: /etc/init.d/$NAME {start|stop|reload|restart}"
    exit 1
    ;;
esac

if [ $? -eq 0 ]; then
	echo .
	exit 0
else
	echo " failed"
	exit 1
fi

