#!/bin/bash

. /etc/rc.conf
. /etc/rc.d/functions
. /etc/conf.d/postgresql

case "$1" in
  start)
    stat_busy "Starting PostgreSQL"
    
    # initialization
    if [ ! -d $PGDATA ]; then
	    echo "Data directory ($PGDATA) missing!"
	    stat_fail
	    exit 1
    fi

    # start the process
    su - postgres -c "/usr/bin/pg_ctl -D $PGDATA -o '-i' -l $PGLOG -W start"
    if [ $? -gt 0 ]; then
      stat_fail
    else
      add_daemon postgresql
      stat_done
    fi
    ;;
  stop)
    stat_busy "Stopping PostgreSQL"
    su - postgres -c "/usr/bin/pg_ctl -D $PGDATA -l $PGLOG -w stop -m fast"
    if [ $? -gt 0 ]; then
      stat_fail
    else
      rm_daemon postgresql
      stat_done
    fi
    ;;
  reload)
    stat_busy "Reloading PostgreSQL configuration"
    su - postgres -c "/usr/bin/pg_ctl -D $PGDATA -l $PGLOG -w reload"
    if [ $? -gt 0 ]; then
      stat_fail
    else
      stat_done
    fi
    ;;
  status)
    su - postgres -c "/usr/bin/pg_ctl -D $PGDATA -l $PGLOG -w status"
    ;;
  restart)
    $0 stop
    $0 start
    ;;
  *)
    echo "usage: $0 {start|stop|restart|status}"  
    ;;
esac

exit 0
