#!/bin/bash

# SCRIPT_DIR is the bin folder of abssolute structure
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

# APP_HOME is the Server folder of the abssolute structure
APP_HOME=$SCRIPT_DIR/..
APP_HOME=$(builtin cd $APP_HOME; pwd)

# JAVA_HOME is set 2 folders behind the Server, in a jre folder
JAVA_HOME=$APP_HOME/jre

# FOLLOW_SERVER_LOGS is a parameter that is used to follow the logs of the server after start
FOLLOW_SERVER_LOGS=false

# Starting arguments
export CUSTOM_ARGUMENTS="-Xmx512m" 
export JAVA_ARGUMENTS="-XX:+HeapDumpOnOutOfMemoryError -Dlog_folder=$APP_HOME/logs -Dlogging.config=$APP_HOME/config/logback.xml"
export CLASSPATH="$APP_HOME/lib/*"
export JAVA_CLASS="-jar $APP_HOME/lib/ConnSolace.jar"
export APPLICATION_ARGUMENTS="--spring.config.location=$APP_HOME/config/application.properties"

for arg in "$@"; do
    case $arg in
        FOLLOW_SERVER_LOGS=*)
            FOLLOW_SERVER_LOGS="${arg#*=}"
            ;;
        CUSTOM_ARGUMENTS=*)
            CUSTOM_ARGUMENTS="${arg#*=}"
            ;;
        JAVA_ARGUMENTS=*)
            JAVA_ARGUMENTS="$JAVA_ARGUMENTS ${arg#*=}"
            ;;
        APPLICATION_ARGUMENTS=*)
            APPLICATION_ARGUMENTS="$APPLICATION_ARGUMENTS ${arg#*=}"
            ;;
    esac
done

touch $SCRIPT_DIR/ContainerLog.log

# Evaluate the new value of JAVA_ARGUMENTS if RMI_SERVER_HOSTNAME was passed
export JAVA_ARGUMENTS=$(eval "echo $JAVA_ARGUMENTS")

cd $APP_HOME/lib
echo "Starting application..."
nohup $JAVA_HOME/bin/java $CUSTOM_ARGUMENTS $JAVA_ARGUMENTS $JAVA_CLASS $APPLICATION_ARGUMENTS > $SCRIPT_DIR/ContainerLog.log 2>&1 &

if [ "$FOLLOW_SERVER_LOGS" == true ]; then
    tail -F $SCRIPT_DIR/ContainerLog.log
else
	exit 0
fi
