#!/bin/sh
#
# postgres      This shell script takes care of starting and stopping
#               postgres.
#
#		The real SUBSYS is taken from the name of the script
#		valid names are any_name or [SK][0-9][0-9]any_name
#		If you want to setup multiple postgres servers you only
#		need to link this file to another name and create a
#		corresponding /etc/sysconfig/daemons/SUBSYS file with 
#		another PGPORT.
#
#		The PGDATADIR gets initialized if it doesn't exist and
#		PGAUTOINIT is set to 'yes'.
#

PATH=/bin:/usr/bin:/sbin:/usr/sbin:/home/postgres/bin
NAME=postmasterd
DAEMON=/home/postgres/bin/$NAME

INITDB=/home/postgres/bin/initdb
PGLOGFILE=/var/log/postgres.d/messages
PGBINDIR=/home/postgres/bin
PGLIBDIR=/home/postgres/lib
POSTGRESHOME=/home/postgres
BINDIR=/home/postgres/bin
cd $BINDIR



# Source function library INCLUDING /etc/sysconfig/daemons/$SUBSYS.
. /etc/rc.d/init.d/functions

## Source networking configuration.
#. /etc/sysconfig/network
#
## Check that networking is up.
#[ ${NETWORKING} = "no" ] && exit 0

[ "$PGDATADIR" ] || PGDATADIR=/home/postgres/data
[ -f $DAEMON ] || exit 0

init_database() {
  # Initialize PGDATADIR (if it isn't done yet) 
  #cd /
  date +"%c initializing $PGDATADIR" >> $PGLOGFILE	
  echo -n "Initializing $IDENT services:"
  su -c "export PATH='$PATH:$PGBINDIR'; \
         $INITDB --pglib=$PGLIBDIR --pgdata=$PGDATADIR >> $PGLOGFILE 2>&1 " \
	postgres 
  if [ $? = 0 ] ; then
    echo -n " datadir=$PGDATADIR"
  else
    echo " failed (see $PGLOGFILE)"
    echo "remove $PGDATADIR completely if you want to retry" >> $PGLOGFILE
    exit 1
  fi
  echo "."
}

date +"%c $1" >> $PGLOGFILE	
# See how we were called.
case "$1" in
 start)
  [ -e /var/lock/subsys/$SUBSYS ] && exit 1

  # Start daemon.
  if [ "$PGAUTOINIT" = "yes" -a  ! -d "$PGDATADIR"  ] ; then
    init_database
  fi
	
  if [ -d "$PGDATADIR" ]; then
    echo -n "Starting $IDENT services (on port #$PGPORT): "
    start-stop-daemon -S -x $DAEMON -n $NAME -- \
       -p $PGPORT -D $PGDATADIR -o "-o $PGLOGFILE" \
       $OPTIONS 3>/var/run/$SUBSYS.pid &
    # postmaster should get the -S option, but it forks internally then
    # so the pid will be unknown :-(
    sleep 1
    touch /var/lock/subsys/$SUBSYS
    echo "."
  elif [ "$PROBABLY" = "goofing" ]; then
    echo "postgres not configured: Skipped!"
  fi
  ;;

 stop)
  # Stop daemons.
  [ -f /var/lock/subsys/$SUBSYS ] || exit 0
  if [ -f /var/run/$SUBSYS.pid ]; then
    echo -n "Shutting down $IDENT: "
    start-stop-daemon -K -p /var/run/$SUBSYS.pid 
    echo "."
  fi
  rm -f /var/lock/subsys/$SUBSYS
  ;;

 *)
  echo "Usage: postgres {start|stop}"
  exit 1
  ;;
esac

exit 0

