#!/bin/sh

# This file belongs in /etc/init.d where it will be run
# on system startup and shutdown to start the
# Firebird database server daemon


# This init script contains functions specific for debian
# init scripts.

### BEGIN INIT INFO
# Provides:          firebird2.5-superclassic
# Required-Start:    $remote_fs $syslog $named
# Required-Stop:     $remote_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start firebird superclassic server
# Description:       Start the firebird guardian process (fbguard)
#                    which starts the actual firebird server process
#                    (fb_smp_server) and makes sure there is always one running
### END INIT INFO


# Source LSB function library.
. /lib/lsb/init-functions

set -u

FB_VER="2.5"
FB_FLAVOUR="superclassic"

FUNCTIONS="/usr/share/firebird${FB_VER}-common/functions.sh"
[ -e "$FUNCTIONS" ] || exit 0
. "$FUNCTIONS"

FBRunUser=firebird
PIDFILE="$RUN/fbserver.pid"
FB_OPTS="-daemon -forever -pidfile $PIDFILE"
NAME="Firebird $FB_VER $FB_FLAVOUR server"

# Check the guardian is there and is executable.
FBGUARD=/usr/sbin/fbguard
FBSERVER=/usr/sbin/fb_smp_server
[ -x $FBGUARD ] && [ -x $FBSERVER ] || exit 0

# Check to see if server is enabled
ENABLE_FIREBIRD_SERVER="no"    # disabled by default
[ -r "$DEFAULT" ] && . "$DEFAULT"

# workaround of splashy's #400598
# define RUNLEVEL to avoind unbound variable error
RUNLEVEL=${RUNLEVEL:-}

unset ISC_USER
unset ISC_PASSWORD

# See how we were called.
case "${1:-}" in
    start)
    if [ "$ENABLE_FIREBIRD_SERVER" != "yes" ];
    then
        log_warning_msg "Not starting $NAME"
        log_warning_msg "Use \`dpkg-reconfigure firebird$FB_VER-$FB_FLAVOUR' to enable"
        RETVAL=0
    else
        if pidof $FBGUARD > /dev/null; then
            log_success_msg "$NAME already running"
            RETVAL=0
        else
            log_action_begin_msg "Starting $NAME"
            create_var_run_firebird
	    # remove stale pid file
	    rm -f $PIDFILE
            start-stop-daemon --start --quiet --chuid $FBRunUser --pidfile $PIDFILE --exec $FBGUARD -- $FB_OPTS 2>&1 | ( grep -v 'server has been successfully started' || true )
            RETVAL=$?
            log_action_end_msg $RETVAL
        fi
    fi
    ;;

    stop)
    if pidof $FBGUARD > /dev/null; then
        log_action_begin_msg "Stopping $NAME"
	start-stop-daemon --stop --quiet --oknodo --retry 10 --exec $FBGUARD \
	    && \
	start-stop-daemon --stop --quiet --oknodo --retry 15 --exec $FBSERVER --pidfile $PIDFILE

        RETVAL=$?
        log_action_end_msg $RETVAL
    else
        log_success_msg "$NAME not running"
        RETVAL=0
    fi
    ;;

    restart|force-reload)
    $0 stop && $0 start
    RETVAL=$?
    ;;

    status)
    pidof $FBGUARD > /dev/null
    RETVAL=$?
    ;;

    *)
    echo "Usage: firebird {start|stop|restart|force-reload|status}"
    RETVAL=2
    ;;
esac

exit $RETVAL

