#! /bin/sh
#
# $Id: dbbalancer.init,v 1.4 2001/12/23 09:41:04 karora Exp $
#
# This init script for DBBalancer was written for Debian by Andrew McMillan.
#
# Loosely based on all those pre-existing scripts, but designed
# to cope with some of the foibles of DBBalancer as well.
#
#  set -o xtrace

PATH=/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/bin/dbbalancerd
CONFDIR=/etc/dbbalancer/conf.d
PIDDIR=/var/run/dbbalancer
NAME=dbbalancer
DESC="Database Balancer"

test -f $DAEMON || exit 0


function start_dbbalancer() {
  for FN in ${CONFDIR}/* ; do
    [ ! -f ${FN} ] && continue;

    NAME=`basename "$FN"`
    ACTION=`basename "$FN" -w`
    if [ "$ACTION" = "$NAME" ]; then
      ACTION=reader
      OPTION=-r
    else
      ACTION=writer
      OPTION=-w
    fi
    
    PORTNUM=`grep $ACTION-port "${FN}" | cut -f2 -d=`
    echo -n "$NAME($PORTNUM) "

    start-stop-daemon -p "${PIDDIR}/dbbalancer-$PORTNUM.pid" --quiet --start --exec $DAEMON -- -p ${PIDDIR} -f ${FN} $OPTION -k /var/run/postgresql >/dev/null 2>&1
  done
}

#
# Note: we only stop the ones we have configuration for
#
function stop_dbbalancer() {
  for FN in ${PIDDIR}/dbbalancer-*.pid ; do
    [ ! -f ${FN} ] && continue;
    PORTNUM=`basename "${FN}" .pid | cut -f2 -d-`
    CONF=`grep -l "writer-port.*${PORTNUM}" /etc/dbbalancer/conf.d/*-w` || true
    if [ "${CONF}" = "" ]; then
      CONF=`grep -l "reader-port.*${PORTNUM}" /etc/dbbalancer/conf.d/* | grep -v '\-w$'`
    fi
    CONF=`basename ${CONF}`
    echo -n "${CONF}(${PORTNUM}) "
    start-stop-daemon --stop --pidfile $FN --exec $DAEMON $@ || true
  done
  echo -n " "
}


set -e

case "$1" in
  start)
	  echo -n "Starting $DESC: "
    start_dbbalancer
	  echo done
	;;
  stop)
 	  echo -n "Stopping $DESC: "
    stop_dbbalancer
    echo done
	;;
  restart)
	  $0 stop
	  $0 start
	;;
  # reload)
    # When dbbalancer supports reload we will use the below...
  	# echo -n "Reloading $DESC: "
    # stop_dbbalancer --signal 1
	  # echo done
	# ;;
  *)
	  N=/etc/init.d/$NAME
	  # echo "Usage: $N {start|stop|restart|reload|force-reload}" >&2
	  echo "Usage: $N {start|stop|restart}" >&2
	  exit 1
	;;
esac

exit 0
