#!/sbin/sh
# $Id: postgres,v 1.3 2001/08/29 15:55:11 toor Exp $

LINKS='../rc3.d/S05postgres ../rc0.d/K30postgres'

# The version of PostgreSQL this is for
PGVERSION=7.1.2

PGBASE=/pgsql
PGHOME=$PGBASE/$PGVERSION
BINDIR=$PGHOME/bin
POSTGRES=$BINDIR/postgres
INITDB=$BINDIR/initdb
PGCTL=$BINDIR/pg_ctl
PGUSER=postgres
PGLOGFILE=/var/log/pgsql/pgsql.log

PATH=$BINDIR:$PATH
LD_LIBRARY_PATH=$PGHOME/lib:$LD_LIBRARY_PATH
PGLIB=$PGHOME/lib
PGDATA=$PGBASE/data
export PATH LD_LIBRARY_PATH PGLIB PGDATA

ERRMSG1="ERROR: PostgreSQL not installed in $PGHOME!"
ERRMSG2="ERROR: 'postgres' program not found in $BINDIR!"
ERRMSG3="ERROR: PostgreSQL already running!"
ERRMSG4="ERROR: PostgreSQL not started!"
ERRMSG5="ERROR: Could not create PostgreSQL data directory for initdb!"

OKMSG1="PostgreSQL $PGDATA Initalized."
OKMSG2="PostgreSQL $PGVERSION has started."

if [ ! -d "$PGHOME" ]; then
        /usr/bin/logger -p daemon.err  $ERRMSG1
        exit 1
fi


case "$1" in 
'start')

        # If not found  
        if [ ! -f "$POSTGRES" ]; then
                /usr/bin/logger -p daemon.err $ERRMSG2  
                exit 1
        fi

        # check to see if PostgreSQL is already running
        $PGCTL status > /dev/null 2>&1
        rtn=$?
        if [ $rtn -eq 0 ]; then
                /usr/bin/logger -p daemon.err $ERRMSG3
                exit 2
        fi

        # No existing PGDATA, initdb it.
        if [ ! -d "$PGDATA" ]; then
                /usr/bin/mkdir -p $PGDATA
                rtn=$?
                if [ $rtn -ne 0 ]; then
                        /usr/bin/logger -p daemon.err $ERRMSG5
                        exit 5
                fi
                /usr/bin/chown postgres:postgres $PGDATA
                /usr/bin/su $PGUSER -c \
		  "$INITDB --pgdata=$PGDATA >& /dev/null < /dev/null"
                rtn=$?
                if [ $rtn ]; then
                        /usr/bin/logger -p daemon.info $OKMSG1
                else
                        /usr/bin/logger -p daemon.err $ERRMSG4
                        exit 3
                fi
        fi
        /usr/bin/su $PGUSER -c \
	   "$PGCTL -w -D $PGDATA -o '-i' -l $PGLOGFILE start"
        $PGCTL status > /dev/null 2>&1
        rtn=$?
        if [ $rtn -eq 0 ]; then
                /usr/bin/logger -p daemon.info $OKMSG2
        else
                /usr/bin/logger -p daemon.err $ERRMSG4
                exit 4
        fi
        ;;

'stop')
        /usr/bin/su $PGUSER -c "$PGCTL stop -m smart"
        /usr/bin/sleep 1
        ;;

'links')
	for LINK in ${LINKS} ; do
	    ln -f ${0} ${LINK}
	done
	;;

*)
        echo "Usage: $0 { start | stop | links}"
        exit 1
        ;;
esac
exit 0

