#!/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_REPORTSERVER is a parameter that determine if the starting process should wait for the server or not default is false
WAIT_FOR_REPORTSERVER=false

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

# Starting arguments
export CUSTOM_ARGUMENTS="-Xmx1024m"
export JAVA_ARGUMENTS="-XX:+ShowCodeDetailsInExceptionMessages -Djava.awt.headless=true"
export CLASSPATH="$ABS_HOME/Reportserver/Lib/*"
export JAVA_CLASS="absgroup.reportserver.Main"
export APPLICATION_ARGUMENTS="-NoGui -I $ABS_HOME/Reportserver/Lib"

for arg in "$@"; do
    case $arg in
        WAIT_FOR_REPORTSERVER=*)
            WAIT_FOR_REPORTSERVER="${arg#*=}"
            ;;
        FOLLOW_REPORTSERVER_LOGS=*)
            FOLLOW_REPORTSERVER_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

cd $ABS_HOME/Reportserver/Lib
echo "Starting the Abssolute Report Server server..."
nohup $JAVA_HOME/bin/java $CUSTOM_ARGUMENTS $JAVA_ARGUMENTS $JAVA_CLASS $APPLICATION_ARGUMENTS > $SCRIPT_DIR/ContainerLog.log 2>&1 &


if [ "$WAIT_FOR_REPORTSERVER" == true ]; then
    bash $SCRIPT_DIR/check_reportserver.sh
fi

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