#!/bin/sh

# To start, stop and restart postgres database server for enstore database.
# 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
# This script assumes that all enstore databases are served by one DB server.

if [ "${1:-}" = "-x" ] ; then set -xv; shift; fi
if [ "${1:-}" = "-q" ] ; then export quiet=1; shift; else quiet=0; fi

source /usr/local/etc/setups.sh
if [ $? -ne 0 ]
then 
    echo setup failed
    exit 1
fi


PATH=/usr/sbin:$PATH
config_host=`echo $ENSTORE_CONFIG_HOST | cut -f1 -d\.`
this_host=`uname -n`

# get enstore db parameters
$ENSTORE_DIR/external_distr/extract_config_parameters.py database  | cut -f1,2 -d\: --output-delimiter=" " > /tmp/e_install_database.tmp
while read f1 f2; do eval $f1=$f2; done < /tmp/e_install_database.tmp
rm -rf /tmp/e_install_database.tmp
echo Database Host: ${db_host}
echo Database Port: ${db_port}
echo Database Directory: ${dbarea}
echo Database Name: ${dbname}
echo Database Base Server Owner: $dbserverowner
echo Data Base User: $dbuser

if [ $this_host != $db_host ]
then
    echo You must run this script on ${db_host} only
    exit 1
fi

if [ $1:"x" == "install" ];then
    if [ "`whoami`" != 'root' ]; then
	echo must be root to run "install"
	exit 1
    fi
    . /usr/local/etc/setups.sh
    x=/etc/rc.d/init.d/enstore-db
    rm -f $x; cp $ENSTORE_DIR/bin/enstore-db $x
    cd /etc/rc.d/rc3.d
    x=S86enstore-db
    rm -f $x; ln -s ../init.d/enstore-db $x
    cd /etc/rc.d/rc6.d
    x=K86enstore-db
    rm -f $x; ln -s ../init.d/enstore-db $x
    exit 0
fi    
 

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

if [ -z $POSTGRES_DIR ]
then
    echo "Postgres is not installed on this host. Please istall postgres 
or modify $ENSTORE_DIR/site_specific/config/setup-enstore"
    exit 1
fi

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 $dbarea | 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 $db_port -D $dbarea -i &
			$pg -p $db_port -D $dbarea -i &
		else
			echo enstore-db 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 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|install}"
		;;
esac
exit 0
