#!/bin/bash
#
# Startup script for Derby
#
# chkconfig: 345 94 16
# description: Derby startup script
# to enable on bootup on redhat "chkconfig --level 35 derby on"
# to enable on bootup on debian "update-rc.d derby defaults" or the
# slightly longer (but better run levels) "update-rc.d derby start 91 2 3 4 5  . stop 20 0 1 6 ."


HOMEDIR=/usr/local/derby
DERBY_USER=derby
APPNAME=Derby
RUNCOMMAND=bin/startNetworkServer
STOCOMMAND=bin/stopNetworkServer
LOGFILE=/var/log/derby.log


DERBY_HOME=$HOMEDIR
export DERBY_HOME


GREPSTRING='derbyclient.jar'

if ! grep -qai "$DERBY_USER" /etc/passwd; then
    echo "$DERBY_USER is not a user.  Please create a user account first" >&2
    exit 1
fi

setpslist() {
    if [ ! -z "$GREPSTRING" ]; then
        pslist=`ps a --width=1000 --User "$DERBY_USER" -o  pid,user,command  | grep "$GREPSTRING" | grep -v PID | awk '{printf $1 " "}'`
    else
        pslist=`ps a --width=1000 --User "$DERBY_USER" -o  pid,user,command  | grep "$GREPSTRING" | grep -v PID | awk '{printf $1 " "}'`
    fi
}


start() {
    setpslist
    if [ ! -z "$pslist" ]; then
        echo "$APPNAME already running, can't start it" >&2
        return 1
    fi
    echo -n "Starting $APPNAME: "
    if [ ! -e "$LOGFILE" -a ! -e "`dirname \"$LOGFILE\"`" ]; then
        mkdir -p `dirname "$LOGFILE"`
    fi
    if [ -e "$LOGFILE" ]; then
        mv "$LOGFILE" "$LOGFILE".old
    fi
    touch $LOGFILE
    chown $DERBY_USER $LOGFILE

    chown -R $DERBY_USER $HOMEDIR
    exec su - -p --shell=/bin/sh $DERBY_USER -c "cd $HOMEDIR; $RUNCOMMAND >\"$LOGFILE\"" 2>&1 &
}


killprocesses() {
    setpslist
    if [ -z "$pslist" ]; then
        echo "$APPNAME not running, no need to kill it"
        return 0
    fi
    kill -9 $pslist
    echo "Killed $APPNAME"
    return 0
}

stop() {
    setpslist
    if [ -z "$pslist" ]; then
        echo "$APPNAME not running, no need to stop it"
        return 0
    fi
    echo -n $"Shutting down $APPNAME: "

    suoutput=`su - --shell=/bin/bash -p $DERBY_USER -c "$STOPCOMMAND"`

    kill -SIGTERM $pslist


}

status() {
    setpslist
    if [ ! -z "$pslist" ]; then
        echo -n "$APPNAME ( PIDs $pslist ) is running."
    else
        echo "$APPNAME is stopped"
    fi
}

case "$1" in
    start)
        start
        ;;
     stop)
        stop
        ;;
     restart)
        stop
        sleep 3
        start
        ;;
     kill)
        killprocesses
        ;;
     killstart)
        killprocesses
        start
        ;;
     status)
        status
        ;;
     *)
        echo "Usage: $0 {start|stop|restart|status|kill|killstart}"
     exit 1
esac
exit $?



