#!/bin/bash

if [ "$START_PERF_ANALYZER" = "false" ]; then
    echo "Not starting performance-analyzer-agent"
    exit 0
fi

if [ -z "$1" ]; then
    if [ -z "$ES_HOME" ]; then
        echo "ES_HOME needs to be set or passed in as the first parameter."
        exit 1
    fi
else
    ES_HOME=$1
fi

if [ -z "$2" ]; then
    if [ -z "$JAVA_HOME" ]; then
        echo "JAVA_HOME needs to be set or passed in as the second parameter."
        exit 1
    fi
else
    JAVA_HOME=$2
fi

if ! echo $* | grep -E '(^-d |-d$| -d |--daemonize$|--daemonize )' > /dev/null; then
    export JAVA_OPTS=-Des.path.home=$ES_HOME\ -Dlog4j.configurationFile=$ES_HOME/performance-analyzer-rca/pa_config/log4j2.xml
    exec $ES_HOME/performance-analyzer-rca/bin/performance-analyzer-rca
else
    echo 'Starting deamon'
    export JAVA_OPTS=-Des.path.home=$ES_HOME\ -Dlog4j.configurationFile=$ES_HOME/performance-analyzer-rca/pa_config/log4j2.xml
    exec $ES_HOME/performance-analyzer-rca/bin/performance-analyzer-rca &

    pid=$!
    PID_LOC=/tmp/performance-analyzer-agent
    if [ -n "$4" ]; then
        PID_LOC=$4
    fi

    if ! ps -p $pid > $PID_LOC ; then
        exit 1
    fi
fi
