#!/bin/sh

# determine location
# resolve links - $0 may be a softlink
PRG="$0"

while [ -h "$PRG" ]; do
  ls=`ls -ld "$PRG"`
  link=`expr "$ls" : '.*-> \(.*\)$'`
  if expr "$link" : '/.*' > /dev/null; then
    PRG="$link"
  else
    PRG=`dirname "$PRG"`/"$link"
  fi
done

# Get standard environment variables
PRGDIR=`dirname "$PRG"`

JAVA=`which java`
SERVER_HOME=${PRGDIR}/server
SERVER_LOG=$SERVER_HOME/standalone/log
H2_PIDFILE=$SERVER_LOG/h2.pid
JBOSS_PIDFILE=$SERVER_LOG/jboss.pid; export JBOSS_PIDFILE
LAUNCH_JBOSS_IN_BACKGROUND=true; export LAUNCH_JBOSS_IN_BACKGROUND

[ -n "$JAVA" ] || { echo "No Java Runtime Environment found" && exit 1; }

cd ${PRGDIR}

if [ -z "$1" ] ; then
    echo "usage: $0 start|stop" >&2
    exit 1
fi

# process command
case "$1" in
    'start')
        echo "Start database .."
        nohup $JAVA -cp $SERVER_HOME/modules/com/h2database/h2/main/h2-1.3.161.jar org.h2.tools.Server -baseDir ./data > $SERVER_LOG/h2.out &
        echo $! > $H2_PIDFILE
        echo "  The databse is now starting, check output in $SERVER_LOG/h2.out"
        echo " "

        sleep 3

        echo "Start Flarmradar Server .."
        nohup /bin/sh $SERVER_HOME/bin/standalone.sh > /dev/null &
        echo "  The server is now starting, check output in $SERVER_LOG/server.log"
        echo " "
        ;;
    'stop')
	[ -f $JBOSS_PIDFILE ] && { echo "Shutdown Flarmradar server" && kill `cat $JBOSS_PIDFILE`; }
        sleep 10
        [ -f $H2_PIDFILE ] && { echo "Shutdown database" && kill `cat $H2_PIDFILE` && rm $H2_PIDFILE; }
        ;;
    *)
        echo "usage: $0 start|stop" >&2
        exit 1
        ;;
esac

exit 0

