#!/bin/sh
# chkconfig: 2345 55 45
### BEGIN INIT INFO
# Provides:          firebird
# Required-Start:    $local_fs
# Required-Stop:     $local_fs
# Should-Start:      $network
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start firebird at boot time
# Description:       Enable service provided by firebird.
# X-Start-Before:    
# X-Stop-After:      
# X-Timesys-Start-Number:  55
# X-Timesys-Stop-Number:  45
### END INIT INFO

PATH=/usr/bin:/usr/sbin:/bin:/sbin:/usr/scripts

fb_install_prefix=/usr
INSTANCE=default
FBRunUser=firebird
runDir=/var/run/firebird
lockDir=/tmp/firebird

FIREBIRD_LOG=/var/log/firebird
FIREBIRD_SECURITY_DB=/var/lib/firebird/security3.fdb


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

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
}

initial_setup() {

    if [ -z "$(grep ^firebird /etc/passwd 2>/dev/null)" ]; then
      echo "$0: Creating system user 'firebird' with generic settings.  Review and modify as required."
      yes '' | adduser firebird >/dev/null 2>&1 || yes '' | useradd firebird >/dev/null 2>&1
    fi

    makeFbDir $runDir
    makeFbDir $lockDir 0770

    if [ -f $FIREBIRD_SECURITY_DB ]; then
            chown $FBRunUser:$FBRunUser $FIREBIRD_SECURITY_DB
    fi

    if [ -d $FIREBIRD_LOG ]; then
            chown $FBRunUser:$FBRunUser $FIREBIRD_LOG
    fi

ISC_USER=
ISC_PASSWORD=
export ISC_USER ISC_PASSWORD

}

case "$1" in
  start)
	initial_setup
	printf %s "Starting $FULLNAME: "
	su $FBRunUser -c "fbguard -pidfile $pidfile -daemon -forever" 
	echo "started."
	RETVAL=$?
	;;
  stop)
	printf %s "Stopping $FULLNAME: "
	if [ -f $pidfile ]
	then
		kill `cat $pidfile`
	fi
	echo "stopped."
	RETVAL=$?
	;;
  status)
	if [ -f $pidfile ]
	then
		pid=`cat $pidfile`
    	if kill -0 $pid >/dev/null 2>&1 ; then
		echo "$FULLNAME is running, pid $pid"
	else
		echo "$FULLNAME is stopped."
	fi
	fi
	;;
  restart|reload)
	$0 stop
	sleep 1
	$0 start
	RETVAL=$?
	;;
  *)
	echo "Usage: firebird {start|stop|status|restart|reload}"
	exit 1
esac

exit $RETVAL

