#!/bin/sh

###############################################################
# Copyright (c) Virtimo AG, Germany.
# https://www.virtimo.de
# All rights reserved.
#
# Script to start OpenSearch and Karaf
###############################################################

PRG="$0"
CONSOLE_MODE="$1"

while [ -h "$PRG" ] ; do
  ls=$(ls -ld "$PRG")
  link=$(expr "$ls" : '.*-> \(.*\)$')
  if expr "$link" : '/.*' > /dev/null; then
    PRG="$link"
  else
    PRG=$(dirname "$PRG")/"$link"
  fi
done

PRGDIR=$(dirname "$PRG")

## Help function ##
show_help() {
	echo "Starts BPC OpenSearch and Karaf"
	echo "Usage: start_bpc.sh [--console]"
	echo
	echo "	-h, --help		Display this help and exit"
	echo
 	echo "	--console		An optional parameter to open Karaf in active console session"
	echo " 				By default Karaf opens without an active console session"
	echo
	echo "See also https://docs.virtimo.net/de/bpc-docs/latest/core/admin/operation/start-stop.html"
	echo
}

## Show help ##
# If param is -h ,--help or anything other than --console then display help #
if [ "$CONSOLE_MODE" = "-h" ] || [ "$CONSOLE_MODE" = "--help" ]; then
	show_help
	exit 1
fi
if [ "$CONSOLE_MODE" ] && [ "$CONSOLE_MODE" != "--console" ]; then
	show_help
	exit 1
fi

## the used external scripts ##
EXECUTABLE_OPENSEARCH="${PRGDIR}/../opensearch/bin/opensearch"

KARAF_STATUS="${PRGDIR}/../karaf/bin/status"

## Function to find OpenSearch pid ##
echo_opensearch_pid() {
    PATTERN_CHECK="org.opensearch.bootstrap.OpenSearch"

    if [ "$(uname)" = "Darwin" ]; then
        PIDS1=$(ps u -U "$USER" | grep -E ".* [0-9]+ .*[j]ava .*${PATTERN_CHECK}" | awk '{ print $2 }')
    else
        PIDS1=$(ps -u "$USER" u | grep -E ".* [0-9]+ .*[j]ava .*${PATTERN_CHECK}" | awk '{ print $2; }')
    fi

	  # make sure result is a number
    echo "$PIDS1" | grep -E "^[1-9][0-9]*" > /dev/null
	  if [ $? -gt 0 ]; then
		    echo ""
	  else
		    echo "$PIDS1"
	  fi
}

## Function to find Karaf status ##
get_karaf_status() {
	"$KARAF_STATUS"
}

#Start OpenSearch
#Check if already running
OPENSEARCH_PID=$(echo_opensearch_pid)
if [ -z "${OPENSEARCH_PID}" ]; then
    echo "Starting OpenSearch ..."
    "$EXECUTABLE_OPENSEARCH" -d
    echo "OpenSearch started"
else
    echo "OpenSearch already running"
fi

#Start Karaf
#Check if already running
STATUSMESSAGE=$(get_karaf_status)
STATUS=$?
if [ $STATUS -eq 1 ] || [ $STATUS -eq 3 ]; then
    echo "Starting Karaf ..."

    if [ "$CONSOLE_MODE" = "--console" ]; then
        # foreground
        "${PRGDIR}/../karaf/bin/karaf"
        # this will be called when Karaf stops
        "${PRGDIR}/stop_bpc.sh"
    else
        # background
        "${PRGDIR}/../karaf/bin/start"
        echo "Karaf started"
    fi

elif [ $STATUS -eq 0 ]; then
    echo "Karaf already running"
else
    echo "Unable to start Karaf"
fi
