#!/bin/sh

# description: Start/Stop firebird database server

# To run more instances of firebird:
#   Copy /usr/local/firebird somewhere
#   Copy this script under a new name
#   Change INSTANCE and FIREBIRD below (all instance names should be unique)
#   Edit the copied firebird.conf to change at least RemoteServicePort
INSTANCE=default
FIREBIRD=/usr/local/firebird

# No changes needed below for multiple instances
FBRunUser=firebird

makeFbDir() {
	mDir=${1}
	mode=${2}
	if [ ! -d $mDir ]; then
		rm -rf $mDir
		mkdir $mDir
		if [ "$mode" ]; then
			chmod $mode $mDir
		fi
	fi
	chown $FBRunUser:$FBRunUser $mDir
}
runDir=/var/run/firebird
makeFbDir $runDir
lockDir=/tmp/firebird
makeFbDir $lockDir 0770

pidfile="$runDir/$INSTANCE.pid"
FULLNAME="Firebird server [$INSTANCE]"
LD_LIBRARY_PATH=$FIREBIRD/lib

export FIREBIRD LD_LIBRARY_PATH

GUARDIAN=$FIREBIRD/bin/fbguard
if [ ! -x $GUARDIAN ]; then
	GUARDIAN=/usr/local/firebird/bin/fbguard
fi

# See how we were called.
case "$1" in
  start)
	echo -n "Starting $FULLNAME: "
	echo "$GUARDIAN -pidfile $pidfile -daemon -forever" | su $FBRunUser
	RETVAL=$?
	;;
  stop)
	echo -n "Stopping $FULLNAME: "
	if [ -f $pidfile ]
	then
		kill `cat $pidfile`
	fi
	echo "stopped."
	RETVAL=$?
	;;
  status)
	if [ -f $pidfile ]
	then
		pid=`cat $pidfile`
    	ps -p $pid >/dev/null 2>&1
		RETVAL=$?
	else
		RETVAL=1
	fi
	if [ $RETVAL -eq 0 ]
	then
		echo "$FULLNAME is running, pid $pid"
	else
		echo "$FULLNAME is stopped."
	fi
	;;
  restart|reload)
	$0 stop
	sleep 1
	$0 start
	RETVAL=$?
	;;
  *)
	echo "Usage: firebird {start|stop|status|restart|reload}"
	exit 1
esac

exit $RETVAL

