#!/bin/bash

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

# APP_HOME is the application folder
APP_HOME=$SCRIPT_DIR/..
APP_HOME=$(builtin cd $APP_HOME; pwd)

# JAVA_HOME is set inside the APP_HOME
JAVA_HOME=$APP_HOME/jre

# FOLLOW_LOGS is a parameter that is used to follow the logs of the application after start
FOLLOW_LOGS=false
LOGS_DIR="${APP_HOME}/logs"

[ ! -d "$LOGS_DIR" ] && mkdir -p "$LOGS_DIR"

# Starting arguments
export JMX_PORT="50173"
export CUSTOM_ARGUMENTS="-Xmx512m" 
export JAVA_ARGUMENTS="-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=$LOGS_DIR -Dlog_folder=$LOGS_DIR -Dlogging.configurationFile=$APP_HOME/config/log4j2.xml -Dcom.sun.management.jmxremote.port=$JMX_PORT -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false"
export CLASSPATH="$APP_HOME/lib/*"
export JAVA_CLASS="-jar $APP_HOME/lib/LocalPrintServer.jar"
export APPLICATION_ARGUMENTS="--spring.config.location=$APP_HOME/config/application.properties"

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

# Evaluate the new value of JAVA_ARGUMENTS
export JAVA_ARGUMENTS=$(eval "echo $JAVA_ARGUMENTS")

cd $APP_HOME
echo "Starting application..."

nohup $JAVA_HOME/bin/java $CUSTOM_ARGUMENTS $JAVA_ARGUMENTS $JAVA_CLASS $APPLICATION_ARGUMENTS > $LOGS_DIR/start_application.log 2>&1 &

if [ "$FOLLOW_LOGS" == true ]; then
    tail -F $LOGS_DIR/start_application.log
else
	exit 0
fi

