#!/bin/sh
# rhdb	This is the init script for starting up the PostgreSQL database service
#       used as the primary data source by the RHAPS JOnAS examples
#
# chkconfig: 2345 75 25
# description: The PostgreSQL backend daemon for RHAPS default datasource.
# processname: postmaster
# pidfile: /var/run/rhdb-jonas.pid

# This script is slightly unusual in that the name of the daemon (postmaster)
# is not the same as the name of the service (rhdb or rhdb-*)

# This script is based on a community version maintained by Lamar Owen

                                                                                
# Find the name of the script
# The name of this service is the script name
# But be careful with the boot case where we have a Snn prefix
NAME=`basename $0`
if [ ${NAME:0:1} = "S" -o ${NAME:0:1} = "K" ]
then
        NAME=${NAME:3}
fi

# Source init scripts function library.
INITD=/etc/rc.d/init.d
. $INITD/functions

# Set the default values for the configuration variables
# Use the RPM installed paths for PGDATA and PGENGINE
# The default PGLOG discards log output
# No options are passed to initdb by default
PGENGINE=/usr/bin
PGDATA=/var/lib/pgsql/data
unset PGDATA2
unset PGDATA3
unset PGDATA4
unset PGDATA5
unset PGDATA6
unset PGDATA7
unset PGDATA8
unset PGDATA9
PGLOG=/dev/null
PGINITOPTIONS=""

# Now let the /etc/sysconfig settings override the defaults
. /etc/sysconfig/${NAME}

# Check that networking is up.
# Pretty much need it for postmaster.
. /etc/sysconfig/network
if [ "${NETWORKING}" = "no" ]
then
	echo $"PostgreSQL requires that networking be enabled."
	exit 1
fi

# Check for the actual postmaster executable
if [ ! -f $PGENGINE/postmaster ]
then
	echo $"No postmaster executable found."
	exit 1
fi

# Init() can be called by itself or by start() so it does not print messages

init() {
	# Do not initialize if there is a data area in there already
	# One must remove it by hand. We do it this way to avoid accidents.
	if [ -f $PGDATA/PG_VERSION ] && [ -d $PGDATA/base ]
	then
		echo $"An existing database was found; no initialization done."
		# FIXME: We cannot just exit here.  We must print FAIL first
		# Maybe we should return 1 so the caller tests for it...
		return 1
	fi

    # Even if there is only a base subdirectory we don't do it.
    # The PG_VERSION must have been removed by accident
	# but valuable data still remains in the base subdirectory.
    # One must remove it by hand. We do it this way to avoid accidents.
    if [ -d $PGDATA/base ]
    then
        echo $"An existing base subdirectory was found (PG_VERSION is missing?); no initialization done."
		return 1
    fi
    
	if [ ! -d $PGDATA ]
	then
		mkdir -p $PGDATA
		chown postgres.postgres $PGDATA
	fi
	
	# Only locale supported is C (no locale)
	echo "export -n LANG LC_ALL LC_CTYPE LC_COLLATE LC_NUMERIC LC_CTYPE LC_TIME" > $PGDATA/../initdb.i18n
	echo "export LANG=C" >> $PGDATA/../initdb.i18n
	
	# Initialize the database
	su -l postgres -s /bin/sh -c "$PGENGINE/initdb --pgdata=$PGDATA > /dev/null 2>&1" < /dev/null

	# Did we succed?  If not, then PG_VERSION was not created
	if [ ! -f $PGDATA/PG_VERSION ]
	then
		return 1
	fi

	# Database Cluster successifuly initialized
	return 0
}

start(){
	PSQL_START=$"Starting the Red Hat Database service: "

	# The first time we start can be right after the RPM installation
	# which does not initialize the data area, so we do it here
	if [ ! -f $PGDATA/PG_VERSION ] || [ ! -d $PGDATA/base ]
	then
		init
	fi

	# Check for postmaster already running...
	pid=`pidof -s $PGENGINE/postmaster`
	if [ $pid ] && $PGENGINE/pg_ctl status -D $PGDATA > /dev/null 2>&1
	then
		echo $"A postmaster is already running."
	else
		#all systems go -- remove any stale lock files
		rm -f /tmp/.s.PGSQL.* > /dev/null
		if [ ! -d /var/log/rhdb ]
		then
			mkdir -p /var/log/rhdb
			chown postgres.postgres /var/log/rhdb
		fi
		if [ ! -f /var/log/rhdb/${NAME} ]
		then
			echo "Log file for PostgreSQL ${NAME} service" > /var/log/rhdb/${NAME}
			chown postgres.postgres /var/log/rhdb/${NAME}
		fi
		echo -n "$PSQL_START"
		# We must start the postmaster as the postgres user
		# and we want to make sure we use the /bin/sh
		# We must also preserve the env variables (for the PGDATAn)
		# and make sure we use the pg_ctl and postmaster from the
		# specified PGENGINE
		# The log file is redirected to PGLOG and we don't use the -l
		# postmaster argument because we plan to do log rotation
		# and that will need piping the output through a helper program
		su -l postgres -s /bin/sh -p -c "export PGDATA2=$PGDATA2;$PGENGINE/pg_ctl  -D $PGDATA -p $PGENGINE/postmaster start >> $PGLOG 2>&1" < /dev/null
 		sleep 1
 		pid=`pidof -s postmaster`
 		if [ $pid ]
		then
			success "$PSQL_START"
			touch /var/lock/subsys/${NAME}
			echo $pid > /var/run/${NAME}.pid
			echo
		else
			failure "$PSQL_START"
			echo
		fi
	fi
}

stop(){
	echo -n $"Stopping the Red Hat Database service: "

	su -l postgres -s /bin/sh -c "$PGENGINE/pg_ctl stop -D $PGDATA -s -m fast" > /dev/null 2>&1
	ret=$? 
	if [ $ret -eq 0 ]; then
		echo_success
	else
		echo_failure
	fi
	echo
	rm -f /var/run/${NAME}.pid
	rm -f /var/lock/subsys/${NAME}
}

restart(){
    stop
    start
}

condrestart(){
    [ -e /var/lock/subsys/${NAME} ] && restart || :
}

reload(){
    su -l postgres -s /bin/sh -c "$PGENGINE/pg_ctl reload -D $PGDATA -s" > /dev/null 2>&1
}

# See how we were called.
case "$1" in
  start)
	start
	rc=$?
	;;
  stop)
	stop
	rc=$?
	;;
  status)
	$PGENGINE/pg_ctl -D $PGDATA status
	rc=$?
	;;
  restart)
	restart
	rc=$?
	;;
  condrestart)
	condrestart
	rc=$?
	;;
  reload|force-reload)
	reload
	rc=$?
	;;
  init)
	echo -n $"Initializing database: "
	init
	rc=$?
	if [ $rc -eq 0 ]
	then
		echo_success
	else
		echo_failure
	fi
	;;
  *)
	echo $"Usage: $0 {start|stop|status|restart|condrestart|reload|force-reload|init}"
	exit 1
esac

exit $rc
