#! /bin/sh
#
# Author: Raimund Jacob <jacob@pinuts.de>
# Author: Florian Wolff <florian@donuz.de>
# Based on SuSE scripts.
# Sets error codes as described in LSB:
# 0	  - success
# 1       - generic or unspecified error
# 3       - unimplemented feature (e.g. "reload")
# 5       - program is not installed
# 6       - program is not configured
#

# For some distributions:
### BEGIN INIT INFO
# Provides:          MaxDB
# Required-Start:    $syslog $remote_fs
# X-UnitedLinux-Should-Start: $time ypbind sendmail
# Required-Stop:     $syslog $remote_fs
# X-UnitedLinux-Should-Stop: $time ypbind sendmail
# Default-Start:     3 5
# Default-Stop:      0 1 2 6
# Short-Description: MaxDB database server
### END INIT INFO

#
# Overridden by sourced config file
SDBUSER=sdb
INDEPP=/opt/sdb/indep_prog

# Check for existence of needed config file and read it
MAXDB_CONFIG=/etc/maxdb.conf
test -r $MAXDB_CONFIG || exit 6
. $MAXDB_CONFIG


# Check for missing binaries (stale symlinks should not happen)
XSERVER_BIN=$INDEPP/bin/x_server
test -x $XSERVER_BIN || exit 5

# Use this to run as specified user
if [ `whoami` = $SDBUSER ]; then
  RUN="/bin/sh -c"
else
  RUN="su $SDBUSER -s /bin/sh -c"
fi

# Setup environment
if [ -n LD_ASSUME_KERNEL ]; then
    export LD_ASSUME_KERNEL
fi
LD_LIBRARY_PATH=$INDEPP/web/lib:$INDEPP/lib:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH


case "$1" in
    start)
	echo -n "Starting MaxDB "
	## start the connection server
	$RUN "$XSERVER_BIN start </dev/null"

	## optionally start webservice
	if [ "$MAXDB_STARTWEBTOOLS" = "yes" ]; then
	    (cd $INDEPP/web/pgm && $RUN "./wahttp </dev/null &")
	fi

	## bring up the instances
	for i in $MAXDB_INSTANCES; do
	    inst=`cut -d: -f1 <<<$i`
	    auth=`cut -d: -f2 <<<$i`
	    echo "Starting MaxDB instance $inst ..."
	    $RUN "$INDEPP/bin/dbmcli -d $inst -u $auth db_online"
	done

	# Remember status and be verbose
	;;
    stop)
	echo -n "Shutting down MaxDB "
	## Stop daemon with killproc(8) and if this fails
	## killproc sets the return value according to LSB.

	# bring down the instances
	for i in $MAXDB_INSTANCES; do
	    inst=`cut -d: -f1 <<<$i`
	    auth=`cut -d: -f2 <<<$i`
	    echo "Stopping MaxDB instance $inst ..."
	    $RUN "$INDEPP/bin/dbmcli -d $inst -u $auth db_offline"
	done

	# optionally stop webservice
	if [ "$MAXDB_STARTWEBTOOLS" = "yes" ]; then
	    $RUN "killall wahttp"
	fi

	# and the control server, too
	$RUN "$INDEPP/bin/x_server stop"

	# Remember status and be verbose
	;;
    restart)
	## Stop the service and regardless of whether it was
	## running or not, start it again.
	$0 stop
	$0 start

	# Remember status and be quiet
	;;
    *)
	echo "Usage: $0 {start|stop|restart}"
	exit 3
	;;
esac

