#!/bin/bash

function findScriptDir() {
  CURRENT=$PWD

  DIR=$(dirname "$0")
  cd "$DIR" || exit
  TARGET_FILE=$(basename "$0")

  # Iterate down a (possible) chain of symlinks
  while [ -L "$TARGET_FILE" ]
  do
      TARGET_FILE=$(readlink "$TARGET_FILE")
      DIR=$(dirname "$TARGET_FILE")
      cd "$DIR" || exit
      TARGET_FILE=$(basename "$TARGET_FILE")
  done

  SCRIPT_DIR=$(pwd -P)
  # Restore current directory
  cd "$CURRENT" || exit
}

findScriptDir
#shellcheck source=bin-regular/common.sh

if [[ "$1" = "--help" ]] || [[ "$1" = "-h" ]]; then
    echo "Usage: $0 [-d]"
    echo "  -d, --daemon   Starts Hazelcast in daemon mode"
    exit 0
elif [[ "$1" = "-d" ]] || [[ "$1" = "--daemon" ]]; then
    DAEMON="true"
fi

. "$SCRIPT_DIR"/common.sh

# HAZELCAST_CONFIG holds the configuration path.
# If the the path is relative, it is relative to the Hazelcast installation directory (HAZELCAST_HOME).
# The path can be absolute.
# By default, it is set to $HAZELCAST_HOME/config/hazelcast.xml, with fallback to $HAZELCAST_HOME/config/hazelcast.yaml
# if the xml file is not present.
if [ -z "$HAZELCAST_CONFIG" ]; then
    HAZELCAST_CONFIG="config/hazelcast.xml"
    if [ ! -f "$HAZELCAST_HOME/$HAZELCAST_CONFIG" ]; then
        HAZELCAST_CONFIG="config/hazelcast.yaml"
    fi
    if [ ! -f "$HAZELCAST_HOME/$HAZELCAST_CONFIG" ]; then
        HAZELCAST_CONFIG="config/hazelcast.yml"
    fi

    if [ ! -f "$HAZELCAST_HOME/$HAZELCAST_CONFIG" ]; then
        echo "Configuration file is missing. Create hazelcast.[xml|yaml|yml] in $HAZELCAST_HOME/config or set the HAZELCAST_CONFIG environment variable."
        exit 1
    fi
fi
# if the first character is /, then this is an absolute path, use as is
# otherwise prepend (HAZELCAST_HOME)
if [ "${HAZELCAST_CONFIG:0:1}" != "/" ]; then
  HAZELCAST_CONFIG="$HAZELCAST_HOME/$HAZELCAST_CONFIG"
fi

if [ "${PROMETHEUS_PORT}" ]; then
    echo "Prometheus enabled on port ${PROMETHEUS_PORT}"
    PROMETHEUS="-javaagent:${HAZELCAST_HOME}/lib/jmx_prometheus_javaagent-0.14.0.jar=${PROMETHEUS_PORT}:${HAZELCAST_HOME}/config/jmx_agent_config.yaml"
fi

readJvmOptionsFile "jvm.options"

JAVA_OPTS_ARRAY=(\
$JDK_OPTS \
"-Dhazelcast.logging.type=log4j2" \
"-Dlog4j.configurationFile=file:$HAZELCAST_HOME/config/log4j2.properties" \
"-Dhazelcast.config=$HAZELCAST_CONFIG" \
"-Djet.custom.lib.dir=$HAZELCAST_HOME/custom-lib" \
$PROMETHEUS \
$JVM_OPTIONS \
$JAVA_OPTS \
)

if [ -z "$LOGGING_LEVEL" ]; then
    export LOGGING_LEVEL="INFO"
fi

if [ "$(arch)" == "s390x" ]; then
  export LOGGING_PATTERN="%d [%highlight{\${LOG_LEVEL_PATTERN:-%5p}}{FATAL=red, ERROR=red, WARN=yellow, INFO=green, DEBUG=magenta}][%style{%t{1.}}{cyan}] [%style{%-10c}{blue}]: %m%n"
else
  export LOGGING_PATTERN="%d [%highlight{\${LOG_LEVEL_PATTERN:-%5p}}{FATAL=red, ERROR=red, WARN=yellow, INFO=green, DEBUG=magenta}] [%style{%t{1.}}{cyan}] [%style{%c{1.}}{blue}]: %m%n"
fi

if [ "$HAZELCAST_LICENSE_KEY" ]; then
    LICENSING_OPTS_ARRAY=("-Dhazelcast.enterprise.license.key=${HAZELCAST_LICENSE_KEY}")
fi

echo "########################################"
echo "# JAVA=$JAVA"
echo "# JAVA_OPTS=${JAVA_OPTS_ARRAY[*]}"
echo "# CLASSPATH=$CLASSPATH"
echo "########################################"

if [[ "$DAEMON" = "true" ]]; then
    mkdir -p $HAZELCAST_HOME/logs
    DATE=$(date "+%Y-%m-%d.%H.%M.%S")
    HAZELCAST_LOG="$HAZELCAST_HOME/logs/hazelcast.$DATE.out"
    echo "Starting Hazelcast in daemon mode. Standard out and error will be written to $HAZELCAST_LOG"
    nohup $JAVA "${JAVA_OPTS_ARRAY[@]}" "${LICENSING_OPTS_ARRAY[@]}" -cp "$CLASSPATH" com.hazelcast.core.server.HazelcastMemberStarter > "$HAZELCAST_LOG" 2>&1 &
else
    echo "Starting Hazelcast"
    set -x
    exec $JAVA "${JAVA_OPTS_ARRAY[@]}" "${LICENSING_OPTS_ARRAY[@]}" -cp "$CLASSPATH" com.hazelcast.core.server.HazelcastMemberStarter
fi
