#!/bin/sh

# This is an universal startup script for enstore databases
# It has to be installed in /etc/rc.d/init.d with one of the following
# names: "enstore-db", "accounting-db" and "drivestat-db".
# All links from them have to contain the original name
# for example
#	/etc/rc.d/rc3.d/S86enstore-db -> /etc/rc.d/init.d/enstore-db
#	/etc/rc.d/rc6.d/K01aaaenstore-db -> /etc/rc.d/init.d/enstore-db
# The script name, i.e. $0, is used to determine the database instance

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

# determine the database instance through $0

if [ ! `echo $0 | grep enstore-db` == "" ]
then
	dbinstance=database
elif [ ! `echo $0 | grep accounting-db` == "" ]
then
	dbinstance=accounting_server
elif [ ! `echo $0 | grep drivestat-db` == "" ]
then
	dbinstance=drivestat_server
fi

# get extract_config_parameters.py
enstore_dir=${ENSTORE_DIR}
extract_config=$enstore_dir/external_distr/extract_config_parameters.py

# get database related information

dbhost=`$extract_config $dbinstance | grep dbhost | cut -d: -f 2`

# must be the dbhost
if [ ! `uname -n` == $dbhost ]
then
	echo wrong dbhost: expecting $dbhost, found `uname -n`
	exit 0
fi

dbserverowner=`$extract_config $dbinstance | grep dbserverowner | cut -d: -f 2`

if [ "`whoami`" != $dbserverowner ]
then
	su $dbserverowner -c "$0 $*"
	exit 0
fi

dbarea=`$extract_config $dbinstance | grep dbarea | cut -d: -f 2`
dbport=`$extract_config $dbinstance | grep dbport | cut -d: -f 2`
dbname=`$extract_config $dbinstance | grep dbname | cut -d: -f 2`

pg=`which postmaster`
pg_ctl=`which pg_ctl`
cmd=$1

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