#!/bin/bash

SCRIPT_PATH="$(
  cd "$(dirname "$0")" >/dev/null 2>&1 || exit
  pwd -P
)"

for i in "$@"; do
  case $i in
  -h | --help)
    HELP=true
    ;;
  esac
done

__usage="
 Usage: $(basename "$0") [options]
 Options:
    -h, --help: Print this help
 "

if [ "${HELP}" = true ]; then
  echo "$__usage"
  exit 0
fi

if [ -z ${DOCKER_MODE} ]; then
  export DOCKER_MODE=true
fi

DEFAULT_JVM_OPTS="-XX:+UseContainerSupport -XX:+UseG1GC -XX:MaxRAMPercentage=75.0"
export CMA_SERVER_JAVA_OPTS="${DEFAULT_JVM_OPTS} ${CMA_SERVER_JAVA_OPTS:-"-Xms2g -Xmx4g"}"

# Validate that ssl-server.properties exists and the keystore it references is present.
_ssl_server_props="${CMA_CONF_DIR:-/home/cma/cma-server/conf}/ssl-server.properties"
if [ ! -f "${_ssl_server_props}" ]; then
  echo "ERROR: ${_ssl_server_props} not found."
  echo "       Run 'bin/cma master docker start' which provisions the keystore automatically,"
  echo "       or generate one manually: bin/setup-ssl.sh generate -s master -d docker"
  exit 1
fi
_keystore_path=$(grep -v '#' "${_ssl_server_props}" | sed -E -n 's/cma\.server\.ssl\.key-store=(.*)/\1/p')
_keystore_path="${_keystore_path#file:}"
if [ -z "${_keystore_path}" ] || [ ! -f "${_keystore_path}" ]; then
  echo "ERROR: Keystore '${_keystore_path}' referenced in ${_ssl_server_props} does not exist."
  echo "       Run 'bin/cma master docker start' which provisions the keystore automatically,"
  echo "       or generate one manually: bin/setup-ssl.sh generate -s master -d docker"
  exit 1
fi

bin/cma start --verbose