#!/usr/bin/env bash
#
# Copyright (c) 2025, Cloudera, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

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

CMA_AGENT_HTTP_PORT=${CMA_AGENT_HTTP_PORT:-9090}
CMA_AGENT_HTTPS_PORT=${CMA_AGENT_HTTPS_PORT:-9093}

DEFAULT_CMA_AGENT_START_TIMEOUT=60
CMA_AGENT_START_TIMEOUT="${DEFAULT_CMA_AGENT_START_TIMEOUT}"
DEFAULT_CMA_AGENT_STOP_TIMEOUT=60
CMA_AGENT_STOP_TIMEOUT="${DEFAULT_CMA_AGENT_STOP_TIMEOUT}"
DEFAULT_CMA_MASTER_HOST="localhost"
DEFAULT_CMA_MASTER_GRPC_PORT=8891
DEFAULT_CMA_AUTH_SERVER_PROTOCOL="http"
DEFAULT_CMA_AUTH_SERVER_PORT=9000
DEFAULT_CMA_AGENT_DOCKER_HOST_PORT=9090
VERBOSE=false
SETUP_CMA=false

LOCAL_ENVIRONMENT="local"
DOCKER_ENVIRONMENT="docker"
RUN_ENVIRONMENT=${LOCAL_ENVIRONMENT}

get_agent_profiles() {
  # discovery profile required for gateway-based agent discovery
  echo "$(get_server_profiles),discovery"
}

create_cma_agent_conf() {
  CMA_AGENT_PROFILES=$(get_agent_profiles)

  mkdir -p $CMA_CONF_DIR
  echo 'Create cma-agent.properties ...' | tee -a "$LOG_FILE"
  cat >"${CMA_AGENT_CONF_FILE}" <<EOF
# cma
cma.data.dir=${DATA_DIR}
cma.venv.dir=${VENV_DIR}
cma.log.dir=${LOGS_DIR}

# cma agent
cma.agent.pid.file=${CMA_AGENT_PID_FILE}
cma.agent.log.file=${CMA_AGENT_LOG_FILE}
cma.agent.profiles=${CMA_AGENT_PROFILES}
cma.agent.http.port=${CMA_AGENT_HTTP_PORT}
cma.agent.https.port=${CMA_AGENT_HTTPS_PORT}

# cma master
cma.master.host=${CMA_MASTER_HOST}
cma.master.grpc.port=${CMA_MASTER_GRPC_PORT}

# cma master discovery
cma.master.idp-uri=${CMA_AUTH_SERVER_URI}
cma.master.gateway-uri=${CMA_GATEWAY_URL}
EOF

  # secure config file
  chmod 600 ${CMA_AGENT_CONF_FILE}
}

get_cma_agent_pid() {
  if [ ! -f "${CMA_AGENT_PID_FILE}" ]; then
    echo ''
  else
    cat "${CMA_AGENT_PID_FILE}"
  fi
}

is_cma_agent_running() {
  local pid=$(get_cma_agent_pid)
  if [ -z "${pid}" -o "${pid}" = '' ]; then
    return 1
  fi
  kill -0 "$pid" >/dev/null 2>&1
}

is_ssl_active() {
  if [ -f "${CMA_AGENT_CONF_FILE}" ]; then
    # get active profiles
    local active_profiles=$(get_cma_conf_value "cma.agent.profiles")
    [[ "${active_profiles}" =~ "ssl" ]]
  else
    [ "${CMA_AGENT_SSL}" = true ]
  fi
}

get_cma_agent_http_port() {
  local port=$CMA_AGENT_PORT
  if [ -z "${CMA_AGENT_PORT}" ]; then
    if [ -f "${CMA_AGENT_CONF_FILE}" ]; then
      port=$(get_cma_conf_value "cma.agent.http.port" "${CMA_AGENT_CONF_FILE}")
    else
      port="${CMA_AGENT_HTTP_PORT}"
    fi
  fi
  echo "${port}"
}

get_cma_agent_https_port() {
  local port=$CMA_AGENT_PORT
  if [ -z "${CMA_AGENT_PORT}" ]; then
    if [ -f "${CMA_AGENT_CONF_FILE}" ]; then
      port=$(get_cma_conf_value "cma.agent.https.port" "${CMA_AGENT_CONF_FILE}")
    else
      port="${CMA_AGENT_HTTPS_PORT}"
    fi
  fi
  echo "${port}"
}

get_cma_agent_port() {
  local port=$CMA_AGENT_PORT
  if [ -z "${CMA_AGENT_PORT}" ]; then
    if is_ssl_active; then
      port=$(get_cma_agent_https_port)
    else
      port=$(get_cma_agent_http_port)
    fi
  fi
  echo "${port}"
}

verify_cma_agent_ports() {
  local port=$(get_cma_agent_http_port)
  if ! verify_port "${port}"; then
    echo "HTTP port $port is being used by another process!"
    exit 1
  fi
  if is_ssl_active; then
    port=$(get_cma_agent_https_port)
    if ! verify_port "${port}"; then
      echo "HTTPS port $port is being used by another process!"
      exit 1
    fi
  fi
}

get_cma_agent_protocol() {
  local protocol=http
  if is_ssl_active; then
    protocol=https
  fi
  echo "${protocol}"
}

wait_for_cma_agent_to_start() {
  wait_for_cma_server_to_start "$CMA_AGENT_LOG_FILE" "${CMA_AGENT_START_TIMEOUT}" "AgentApplication"
  if [ $? -ne 0 ]; then
    echo "CMA Agent failed to start!" | tee -a "$LOG_FILE"
    exit 1
  fi
}

cleanup() {
  echo -e '\n'
  if [ "${SETUP_CMA}" = true ]; then
    if ! delete_virtual_env; then
      echo 'Next time the script should be called with the --rebuild option'
    fi
  fi
  echo 'The script is terminated'
  exit 1
}

setup_cma() {
  SETUP_CMA=true
  if is_dev_tty_available; then
    echo -n "Installing the CMA dependencies.." | tee -a "$LOG_FILE"
  else
    echo "Installing the CMA dependencies.." | tee -a "$LOG_FILE"
  fi
  CMA_SETUP_OPTS="--local --profile=${CMA_SERVER_EXTRA_PROFILE} --python-executable=${PYTHON_EXECUTABLE} "
  if [ "$CMA_SERVER_SSL" = true ]; then
    CMA_SETUP_OPTS+="--ssl "
  fi
  if [ "$CMA_SERVER_LDAP" = true ]; then
    CMA_SETUP_OPTS+="--ldap "
  fi
  if [ "$CMA_SKIP_JAVA_CHECK" = true ]; then
    CMA_SETUP_OPTS+="--skip-java-check "
  fi
  if [ "$SKIP_PYTHON_CHECK" = true ]; then
    CMA_SETUP_OPTS+="--skip-python-check "
  fi

  execute_command "$SCRIPT_PATH"/setup.sh ${CMA_SETUP_OPTS}

  if [ -d "${VENV_DIR}" ]; then
    echo "Done." | tee -a "$LOG_FILE"
  else
    echo "Failed." | tee -a "$LOG_FILE"
    exit 1
  fi
}

get_cma_gateway_url_from_input() {
  if [ "${CMA_YES}" != true ]; then
    read -p "Enter the CMA Gateway URL (leave empty to configure master connection manually):" CMA_GATEWAY_URL
  fi
}

get_cma_master_host_from_input() {
  while [ -z "${CMA_MASTER_HOST}" ]; do
    if [ "${CMA_YES}" != true ]; then
      read -p "Enter the hostname of the CMA Master instance [${DEFAULT_CMA_MASTER_HOST}]:" CMA_MASTER_HOST
    fi
    CMA_MASTER_HOST=${CMA_MASTER_HOST:-${DEFAULT_CMA_MASTER_HOST}}
  done
  echo "${CMA_MASTER_HOST}"
}

get_cma_master_grpc_port_from_input() {
  while [ -z "${CMA_MASTER_GRPC_PORT}" ]; do
    if [ "${CMA_YES}" != true ]; then
      read -p "Enter the gRPC port of the CMA Master instance [${DEFAULT_CMA_MASTER_GRPC_PORT}]:" CMA_MASTER_GRPC_PORT
    fi
    CMA_MASTER_GRPC_PORT=${CMA_MASTER_GRPC_PORT:-${DEFAULT_CMA_MASTER_GRPC_PORT}}
  done
  echo "${CMA_MASTER_GRPC_PORT}"
}

get_cma_auth_server_uri_from_input() {
  local default_uri="${DEFAULT_CMA_AUTH_SERVER_PROTOCOL}://${CMA_MASTER_HOST:-${DEFAULT_CMA_MASTER_HOST}}:${DEFAULT_CMA_AUTH_SERVER_PORT}"
  while [ -z "${CMA_AUTH_SERVER_URI}" ]; do
    if [ "${CMA_YES}" != true ]; then
      read -p "Enter the auth server URI of the CMA Master instance [${default_uri}]:" CMA_AUTH_SERVER_URI
    fi
    CMA_AUTH_SERVER_URI=${CMA_AUTH_SERVER_URI:-${default_uri}}
  done
  echo "${CMA_AUTH_SERVER_URI}"
}

start_cma_agent() {

  # load previously saved credentials as defaults
  load_cma_agent_auth_conf
  load_agent_db_conf

  # restore master coordinates and IDP/gateway URIs from existing cma-agent.properties
  if [ -f "${CMA_AGENT_CONF_FILE}" ]; then
    CMA_MASTER_HOST="${CMA_MASTER_HOST:-$(get_cma_conf_value "cma.master.host" "${CMA_AGENT_CONF_FILE}")}"
    CMA_MASTER_GRPC_PORT="${CMA_MASTER_GRPC_PORT:-$(get_cma_conf_value "cma.master.grpc.port" "${CMA_AGENT_CONF_FILE}")}"
    CMA_AUTH_SERVER_URI="${CMA_AUTH_SERVER_URI:-$(get_cma_conf_value "cma.master.idp-uri" "${CMA_AGENT_CONF_FILE}")}"
    CMA_GATEWAY_URL="${CMA_GATEWAY_URL:-$(get_cma_conf_value "cma.master.gateway-uri" "${CMA_AGENT_CONF_FILE}")}"
  fi

  # prompt for gateway URL if not set and master coordinates are unknown
  if [ -z "${CMA_GATEWAY_URL}" ] && [ -z "${CMA_MASTER_HOST}" ]; then
    get_cma_gateway_url_from_input
  fi

  # ensure the agent client secret is available before HMAC verification
  prompt_for_agent_client_secret

  # when gateway discovery is not used — fall back to individual prompts for master coordinates
  if [ -z "${CMA_GATEWAY_URL}" ]; then
    if [ -z "${CMA_MASTER_HOST}" ]; then
      CMA_MASTER_HOST=$(get_cma_master_host_from_input)
    fi
    if [ -z "${CMA_MASTER_GRPC_PORT}" ]; then
      CMA_MASTER_GRPC_PORT=$(get_cma_master_grpc_port_from_input)
    fi
    if [ -z "${CMA_AUTH_SERVER_URI}" ]; then
      CMA_AUTH_SERVER_URI=$(get_cma_auth_server_uri_from_input)
    fi
  fi
  ensure_internal_keystore_password "${CMA_CONF_DIR}"

  prompt_for_agent_secrets

  # create cma-agent.properties file
  if [ ! -f "${CMA_AGENT_CONF_FILE}" ]; then
    read_cma_ssl_conf
    create_cma_agent_conf
    if [ -n "${SSL_PROFILE}" ]; then
      CMA_SERVER_CONF_FILE="${CMA_AGENT_CONF_FILE}"
      add_to_active_profiles "${SSL_PROFILE}" "cma.agent.profiles"
    fi
  else
    # update profiles
    local old_profiles=$(get_cma_conf_value "cma.agent.profiles")
    local new_profiles=$(get_agent_profiles)
    if [ "${old_profiles}" != ${new_profiles} ]; then
      set_cma_conf_value "cma.agent.profiles" "${new_profiles}" "${CMA_AGENT_CONF_FILE}"
      echo "Changed agent profile from ${old_profiles} to ${new_profiles} " | tee -a "$LOG_FILE"
    fi
  fi

  # always (re)write agent-auth.properties so credentials are up-to-date on every start
  create_cma_agent_auth_conf
  create_agent_db_conf

  if ! is_cma_agent_running; then

    if [ "$CMA_SKIP_PORT_CHECK" = true ]; then
      echo "Port(s) verification skipped!" | tee -a "$LOG_FILE"
    else
      verify_cma_agent_ports | tee -a "$LOG_FILE"
      if [ ${PIPESTATUS[0]} -ne 0 ]; then
        echo "Exiting..." | tee -a "$LOG_FILE"
        exit 1
      fi
      echo "Port(s) verification done!" | tee -a "$LOG_FILE"
      CMA_SKIP_PORT_CHECK=true # skip the port check in the cma-agent-server.sh
    fi

    if is_dev_tty_available; then
      echo -n "Starting the CMA Agent.." | tee -a "$LOG_FILE"
    else
      echo "Starting the CMA Agent.." | tee -a "$LOG_FILE"
    fi

    export CMA_AGENT_SERVER_JAVA_OPTS="${CMA_AGENT_SERVER_JAVA_OPTS:-"-Xms2g -Xmx4g"}"
    echo "CMA_AGENT_SERVER_JAVA_OPTS=${CMA_AGENT_SERVER_JAVA_OPTS}" >>"$LOG_FILE"

    umask 027
    export CMA_HOME="${ROOT_DIR}"
    export CMA_AGENT_CONF_FILE
    export CMA_AGENT_LOG_FILE
    export CMA_AGENT_PID_FILE
    execute_command "$ROOT_DIR"/cma-agent/cma-agent-server.sh start

    # check if cma_agent started
    wait_for_cma_agent_to_start

    CMA_SERVER_PROTOCOL=$(get_cma_agent_protocol)
    if [ -z "${CMA_AGENT_PORT}" ]; then
      CMA_AGENT_PORT=$(get_cma_agent_port)
    fi
    echo "The CMA Agent is available at ${CMA_SERVER_PROTOCOL}://localhost:${CMA_AGENT_PORT} " | tee -a "$LOG_FILE"

    if [ "$DOCKER_MODE" = true ]; then
      tail -f "${CMA_AGENT_LOG_FILE}"
    fi
  else
    echo "CMA Agent is running!"
  fi
}

stop_cma_agent() {
  if is_cma_agent_running; then
    export CMA_HOME="${ROOT_DIR}"
    export CMA_AGENT_CONF_FILE
    export CMA_AGENT_PID_FILE
#    export CMA_SERVER_ENV_FILE
    if is_dev_tty_available; then
      echo -n "Stopping the CMA Agent.." | tee -a "$LOG_FILE"
    else
      echo "Stopping the CMA Agent.." | tee -a "$LOG_FILE"
    fi
    execute_command "$ROOT_DIR"/cma-agent/cma-agent-server.sh stop

    # check if cma-agent stopped
    wait_for_cma_agent_to_stop

  else
    echo "CMA Agent is not running!"
  fi
}

reinstall() {
  # stop cma-agent if running
  if is_cma_agent_running; then
    stop_cma_agent
  fi

  # Docker images pre-build the venv with uv during image creation (see cma-agent.dockerfile).
  # Skip venv deletion and recreation to preserve the pre-built environment.
  if [ -f "${VENV_DIR}/.docker-prebuilt" ]; then
    echo "Using pre-built virtualenv in ${VENV_DIR}, skipping reinstall" | tee -a "$LOG_FILE"
    return 0
  fi

  # delete virtual env
  if ! delete_virtual_env; then
    exit 1
  fi
  setup_cma
}

# if called as source code then return
[[ $_ != $0 ]] && return 2>/dev/null

# newer ansible needs locale to be set
export LC_ALL="en_US.UTF-8"

args=("${@}")
for i in "${!args[@]}"; do

  if [ "${skip_next}" = true ]; then
    skip_next=false
    continue
  fi

  case ${args[i]} in
  local)
    RUN_ENVIRONMENT=${LOCAL_ENVIRONMENT}
    unset "args[i]"
    ;;
  docker)
    RUN_ENVIRONMENT=${DOCKER_ENVIRONMENT}
    unset "args[i]"
    ;;
  start)
    ACTION_START=true
    ;;
  stop)
    ACTION_STOP=true
    ;;
  restart)
    ACTION_STOP=true
    ACTION_START=true
    ;;
  setup | rebuild)
    ACTION_REBUILD=true
    ;;
  -p=* | --profile=*)
    CMA_SERVER_EXTRA_PROFILE=${args[i]#*=}
    ;;
  -p | --profile)
    CMA_SERVER_EXTRA_PROFILE="${args[i+1]}"
    skip_next=true
    ;;
  --docker-host-port)
    CMA_AGENT_DOCKER_HOST_PORT="${args[i+1]}"
    unset "args[i]"
    unset "args[i+1]"
    ;;
  -py=* | --python-executable=*)
    PYTHON_EXECUTABLE=${args[i]#*=}
    ;;
  -py | --python-executable)
    PYTHON_EXECUTABLE="${args[i+1]}"
    skip_next=true
    ;;
  --pip-index-url=*)
    CMA_PIP_INDEX_URL=${args[i]#*=}
    ;;
  --pip-index-url)
    CMA_PIP_INDEX_URL="${args[i+1]}"
    skip_next=true
    ;;
  --skip-java-check)
    CMA_SKIP_JAVA_CHECK=true
    ;;
  --skip-python-check)
    SKIP_PYTHON_CHECK=true
    ;;
  --skip-ssl-check)
    CMA_SKIP_SSL_CHECK=true
    ;;
  --skip-port-check)
    CMA_SKIP_PORT_CHECK=true
    ;;
  -n=* | --instance-name=*)
    CMA_INSTANCE_NAME=${args[i]#*=}
    ;;
  -n | --instance-name)
    CMA_INSTANCE_NAME="${args[i+1]}"
    skip_next=true
    ;;
  -ad=* | --app-data-dir=*)
    CMA_APP_DATA_DIR=${args[i]#*=}
    ;;
  -ad | --app-data-dir)
    CMA_APP_DATA_DIR="${args[i+1]}"
    skip_next=true
    ;;
  --start-timeout=*)
    CMA_AGENT_START_TIMEOUT=${args[i]#*=}
    ;;
  --start-timeout)
    CMA_AGENT_START_TIMEOUT="${args[i+1]}"
    skip_next=true
    ;;
  --stop-timeout=*)
    CMA_SERVER_STOP_TIMEOUT=${args[i]#*=}
    ;;
  --stop-timeout)
    CMA_SERVER_STOP_TIMEOUT="${args[i+1]}"
    skip_next=true
    ;;
  --ssl)
    CMA_SERVER_SSL=true
    ;;
  -y | --assumeyes)
    CMA_YES=true
    ;;
  --agent-client-id=*)
    CMA_AGENT_CLIENT_ID=${args[i]#*=}
    ;;
  --agent-client-id)
    CMA_AGENT_CLIENT_ID="${args[i+1]}"
    skip_next=true
    ;;
  --agent-client-secret=*)
    CMA_AGENT_CLIENT_SECRET=${args[i]#*=}
    ;;
  --agent-client-secret)
    CMA_AGENT_CLIENT_SECRET="${args[i+1]}"
    skip_next=true
    ;;
  --auth-server-uri=*)
    CMA_AUTH_SERVER_URI=${args[i]#*=}
    ;;
  --auth-server-uri)
    CMA_AUTH_SERVER_URI="${args[i+1]}"
    skip_next=true
    ;;
  --gateway-url=*)
    CMA_GATEWAY_URL=${args[i]#*=}
    CMA_GATEWAY_URL_EXPLICIT=true
    ;;
  --gateway-url)
    CMA_GATEWAY_URL="${args[i+1]}"
    CMA_GATEWAY_URL_EXPLICIT=true
    skip_next=true
    ;;
  -h | --help)
    HELP=true
    ;;
  -v | --verbose)
    VERBOSE=true
    ;;
  *)
    if [ "${RUN_ENVIRONMENT}" = "${LOCAL_ENVIRONMENT}" ]; then
      echo "Unknown option: ${args[i]}"
      HELP=true
    fi
    ;;
  esac
done

__usage="
Usage: ${CMA_CLI_COMMAND:-$(basename "$0")} [actions] [options]
Available actions:
   local   : Run the CMA Agent in local mode
   docker  : Run the CMA Agent in docker mode
   start   : Start the CMA Agent
   stop    : Stop the CMA Agent
   restart : Restart the CMA Agent
   setup   : Install the dependencies
Options:
   --ssl: Enable ssl for the CMA Agent
   -n,  --instance-name: Set the name of the instance (Default: ${CMA_INSTANCE_NAME})
   -p,  --profile: Set additional profile(s) for the CMA Agent
   -py, --python-executable: Path to python3 executable
   -ad, --app-data-dir: Sets the folder where configs, logs and data are placed for instances (Default: ${CMA_APP_DATA_DIR}})
   --start-timeout: Set timeout for server start (Default: $DEFAULT_CMA_AGENT_START_TIMEOUT seconds)
   --stop-timeout: Set timeout for server stop (Default: $DEFAULT_CMA_SERVER_STOP_TIMEOUT seconds)
   --skip-java-check: Skip java version check. This is not recommended unless the version check fails even though the JAVA_HOME is JDK 11 or later.
   --skip-python-check: Skip python version check. This is not recommended unless the version check fails even though the python version is supported.
   --skip-ssl-check: Skip ssl config check. This is not recommended unless the check fails even though the ssl config is correct.
   --skip-port-check: Skip port(s) check. This is not recommended unless the check fails even though the http/https port(s) are not in use by other processes.
   --docker-host-port: Host port bound to agent UI in docker mode (Default: ${DEFAULT_CMA_AGENT_DOCKER_HOST_PORT})
   --gateway-url: CMA Gateway base URL — derives master host, gRPC port, and auth-server-uri automatically (recommended)
   --agent-client-id: OAuth2 client ID for the CMA Agent (Default: cma-agent)
   --agent-client-secret: OAuth2 client secret for the CMA Agent (required when gRPC auth is enabled)
   --auth-server-uri: OAuth2 auth server URI of the CMA Master instance; overrides gateway discovery (Default: http://<master-host>:${DEFAULT_CMA_AUTH_SERVER_PORT})
   -v, --verbose: Print verbose log
   -h, --help: Print this help
"

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

CMA_INSTANCE_NAME=${CMA_INSTANCE_NAME:-cma-agent} # TODO this should be changed when master-agent becomes the default
CMA_APP_DATA_DIR=${CMA_APP_DATA_DIR:-${HOME}/.cma}
CMA_INSTANCE_DIR=${CMA_APP_DATA_DIR}/${CMA_INSTANCE_NAME}

export CMA_INSTANCE_NAME
export DOCKER_CONTAINER_NAME="${CMA_INSTANCE_NAME:-cma-agent}"
export CMA_CONF_DIR=${CMA_CONF_DIR:-${CMA_INSTANCE_DIR}/conf}
export CMA_LOG_DIR=${CMA_LOG_DIR:-${CMA_INSTANCE_DIR}/logs}
export CMA_DATA_DIR=${CMA_DATA_DIR:-${CMA_INSTANCE_DIR}/data}
export CMA_AGENT_DOCKER_HOST_PORT="${CMA_AGENT_DOCKER_HOST_PORT:-${DEFAULT_CMA_AGENT_DOCKER_HOST_PORT}}"
export CMA_PIP_INDEX_URL
export CMA_AUTH_SERVER_URI="${CMA_AUTH_SERVER_URI:-}"
export CMA_GATEWAY_URL="${CMA_GATEWAY_URL:-}"

source "$SCRIPT_PATH"/common.sh # load commons
create_logs_dir
LOG_FILE="$LOGS_DIR"/$(basename "$0" .sh).log

#CMA_AGENT_CONF_FILE=${CMA_AGENT_CONF_FILE:-"${CMA_CONF_DIR}/cma-agent.properties"}
#CMA_AGENT_CONF_FILE_BAK="${CMA_AGENT_CONF_FILE}.bak"

CMA_AGENT_PID_DIR=${CMA_AGENT_PID_DIR:-${CMA_INSTANCE_DIR}}
CMA_AGENT_PID_FILE="${CMA_AGENT_PID_FILE:-${CMA_AGENT_PID_DIR}/cma-agent-server.pid}"

CMA_AGENT_LOG_FILE=${CMA_AGENT_LOG_FILE:-${CMA_LOG_DIR}/cma-agent-server.log}

echo "SSL configured: ${CMA_SERVER_SSL:-false}" | tee -a "$LOG_FILE"
echo "Vault configured: ${CMA_VAULT:-false}" | tee -a "$LOG_FILE"

if [ -n "${CMA_SERVER_EXTRA_PROFILE}" ]; then
  echo "Additional profile(s): ${CMA_SERVER_EXTRA_PROFILE}" | tee -a "$LOG_FILE"
fi

if [ "${RUN_ENVIRONMENT}" = "${DOCKER_ENVIRONMENT}" ]; then
  # Dispatch once to cma-docker.sh; the original command (start/stop/restart/rebuild)
  # is still present in args and cma-docker.sh will handle all actions correctly.
  ${SCRIPT_PATH}/cma-docker.sh "${args[@]}" --service-type agent
else
  if [ "${ACTION_STOP}" = true ]; then
    stop_cma_agent
  fi

  if [ "${ACTION_REBUILD}" = true ]; then
    reinstall
  fi

  if [ "${ACTION_START}" = true ]; then
    if [ ! -d "${VENV_DIR}" ]; then
      setup_cma
      sleep 1
    fi
    start_cma_agent
  fi
fi
