#!/bin/sh

# To start, stop and restart postgres database server for enstore-db.
# It shall be installed in /etc/rc.d/init.d/enstore-db and linked from
# /etc/rc.d/rc3.d/S86enstore-db and /etc/rc.d/rc6.d/S86enstore-db

# need to be run as user 'products'
if [ "`whoami`" != 'products' ]
then
	su products -c "$0 $*"
	exit 0
fi

# get the host
host=`uname -n | cut -d. -f1`

# get db directory
case $host in
	rip1|gccensrv1)
		db=/diska/enstore-db
		;;
	stkensrv0|cdfensrv0|d0ensrv0|rip6)
		db=/diskb/enstore-db
		;;
	*)
		echo no enstore-db for this node: $host
		exit 0
		;;
esac

# setup postgres
. /usr/local/etc/setups.sh
setup postgres

pg=`which postmaster`
cmd=$1

# what to do?
case $cmd in
	start)
		# make sure there is no other running
		pid=`ps -axw| grep postmaster | grep $db | awk '{print $1}'`
		if [ "${pid}x" == "x" ]
		then
			# take care of the left over pid info, if any
			/bin/rm -f $db/postmaster.pid
			echo $pg -p 8888 -D $db -i &
			$pg -p 8888 -D $db -i &
			sleep 10
		else
			echo enstore-db has already started
		fi
		;;
	stop)
		# find the pid
		pid=`ps -axw| grep postmaster | grep $db | awk '{print $1}'`
		# make sure that we really have a process to kill
		if [ "${pid}x" == "x" ]
		then
			echo enstore-db is not running
		else
			echo kill $pid
			kill $pid
		fi
		;;
	restart)
		$0 stop
		sleep 5
		$0 start
		;;
	*)
		echo "usage: $0 {start|stop|restart}"
		;;
esac
exit 0
