#!/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
PIDFILE=/var/run/postgresql/$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

case "$1" in
  start)
    echo -n "Starting server: $NAME"
    start-stop-daemon --start --pidfile $PIDFILE --exec $DAEMON --chuid $RUNASUSER -- $OPTS 2> /dev/null
    ;;

  stop)
    echo -n "Stopping server: $NAME"
    start-stop-daemon --stop --pidfile $PIDFILE --exec $DAEMON --retry 30
    ;;

  reload | force-reload)
    echo -n "Reloading $NAME configuration"
    start-stop-daemon --stop --pidfile $PIDFILE --exec $DAEMON --signal HUP
    ;;

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

  status)
    start-stop-daemon --status --pidfile $PIDFILE --exec $DAEMON
    status=$?
    if [ $status -eq 0 ]; then
	log_success_msg "pgbouncer is running"
    else
	log_failure_msg "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

