#!/bin/bash

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

if [[ -z "$1" ]]; then
    if [[ -z "$OPENSEARCH_HOME" ]]; then
        echo "OPENSEARCH_HOME needs to be set or passed in as the first parameter."
        exit 1
    fi
else
    OPENSEARCH_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=-Dopensearch.path.home=$OPENSEARCH_HOME\ -Dlog4j.configurationFile=$OPENSEARCH_HOME/performance-analyzer-rca/pa_config/log4j2.xml
    exec $OPENSEARCH_HOME/performance-analyzer-rca/bin/performance-analyzer-rca
else
    echo 'Starting deamon'
    export JAVA_OPTS=-Dopensearch.path.home=$OPENSEARCH_HOME\ -Dlog4j.configurationFile=$OPENSEARCH_HOME/performance-analyzer-rca/pa_config/log4j2.xml
    exec $OPENSEARCH_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