#!/bin/bash

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

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

# SLOT_NUMBER is the slot on which this is created
SLOT_NUMBER=$(echo "$ABS_HOME" | awk -F'/' '{print $(NF-0)}')

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

# WAIT_FOR_SERVER is a parameter that determine if the starting process should wait for the server or not - default is false
WAIT_FOR_SERVER=false

# RMI_SERVER_HOSTNAME is a parameter that is used when starting abssolute with a custom load balancer IP
RMI_SERVER_HOSTNAME=$(hostname)

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

# LOG_FILE is the ServerRollingLog file
LOG_FILE="ServerRollingFile.log"

# Starting arguments
export CUSTOM_ARGUMENTS="-Xmx1024m" 
export JAVA_ARGUMENTS="--add-opens java.base/java.lang=ALL-UNNAMED -XX:+ShowCodeDetailsInExceptionMessages -Djava.rmi.server.hostname=\$RMI_SERVER_HOSTNAME -Djava.awt.headless=true"
export CLASSPATH="$ABS_HOME/Server/Lib/server-impl.jar:$ABS_HOME/Server/Lib/*"
export JAVA_CLASS="-Dloader.path=\"$ABS_HOME/Server/Lib/*\""
export APPLICATION_ARGUMENTS="org.springframework.boot.loader.launch.PropertiesLauncher -G -I $ABS_HOME/Server/Lib --spring.config.location=$ABS_HOME/Server/Config/application.properties"

for arg in "$@"; do
    case $arg in
        FOLLOW_SERVER_LOGS=*)
            FOLLOW_SERVER_LOGS="${arg#*=}"
            ;;
        WAIT_FOR_SERVER=*)
            WAIT_FOR_SERVER="${arg#*=}"
            ;;
        RMI_SERVER_HOSTNAME=*)
            RMI_SERVER_HOSTNAME="${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 if RMI_SERVER_HOSTNAME was passed
export JAVA_ARGUMENTS=$(eval "echo $JAVA_ARGUMENTS")

cd $ABS_HOME/Server/Lib
echo "Starting the Abssolute server..."
nohup $JAVA_HOME/bin/java $CUSTOM_ARGUMENTS $JAVA_ARGUMENTS $JAVA_CLASS $APPLICATION_ARGUMENTS &


if [ "$WAIT_FOR_SERVER" == true ]; then
    bash $SCRIPT_DIR/check_server.sh
fi

if [ "$FOLLOW_SERVER_LOGS" == true ]; then
	while [ ! -f "$ABS_HOME/Server/Log/$LOG_FILE" ]; do
		echo "Waiting for $ABS_HOME/Server/Log/$LOG_FILE to be created..."
		sleep 5
	done
	tail -F "$ABS_HOME/Server/Log/$LOG_FILE"
else
	exit 0
fi
