#!/usr/bin/env bash
#
# Copyright (c) 2023-2026, 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_INSTANCE_NAME=${CMA_INSTANCE_NAME:-cma-server}
CMA_APP_DATA_DIR=${CMA_APP_DATA_DIR:-${HOME}/.cma}

DEFAULT_CMA_SERVER_START_TIMEOUT=30
CMA_SERVER_START_TIMEOUT="${DEFAULT_CMA_SERVER_START_TIMEOUT}"
DEFAULT_CMA_SERVER_STOP_TIMEOUT=30
CMA_SERVER_STOP_TIMEOUT="${DEFAULT_CMA_SERVER_STOP_TIMEOUT}"

SETUP_CMA_SERVER=false
VERBOSE=false
AIRGAPPED=${CMA_AIRGAPPED:-false}

CMA_SKIP_JAVA_CHECK=${CMA_SKIP_JAVA_CHECK:-false}
SKIP_PYTHON_CHECK=${CMA_SKIP_PYTHON_CHECK:-false}

# 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
  start | --start)
    if [ "${RUN_SSL_SETUP}" = true ]; then
      echo "'${args[i]}' conflicts with SSL setup action."
      HELP=true
    else
      ACTION_START=true
      RUN_SSL_SETUP=false
    fi
    unset "args[i]"
    ;;
  stop | --stop)
    if [ "${RUN_SSL_SETUP}" = true ]; then
      echo "'${args[i]}' conflicts with SSL setup action."
      HELP=true
    else
      ACTION_STOP=true
      RUN_SSL_SETUP=false
    fi
    unset "args[i]"
    ;;
  restart | --restart)
    if [ "${RUN_SSL_SETUP}" = true ]; then
      echo "'${args[i]}' conflicts with SSL setup action."
      HELP=true
    else
      ACTION_STOP=true
      ACTION_START=true
      RUN_SSL_SETUP=false
    fi
    unset "args[i]"
    ;;
  rebuild | --rebuild)
    if [ "${RUN_SSL_SETUP}" = true ]; then
      echo "'${args[i]}' conflicts with SSL setup action."
      HELP=true
    else
      ACTION_REBUILD=true
      RUN_SSL_SETUP=false
    fi
    unset "args[i]"
    ;;
  ssl)
    if [ "${RUN_SSL_SETUP}" = false ]; then
      echo "'${args[i]}' conflicts with star/stop/restart/rebuild actions."
      HELP=true
    else
      RUN_SSL_SETUP=true
    fi
    unset "args[i]"
    ;;
  -p=* | --profile=*)
    CMA_SERVER_EXTRA_PROFILE=${args[i]#*=}
    ;;
  -p | --profile)
    CMA_SERVER_EXTRA_PROFILE="${args[i+1]}"
    skip_next=true
    ;;
  -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
    ;;
  # TODO remove this option after GH check is changed
  --ssl)
    CMA_SERVER_SSL=true
    ;;
  --ldap)
    CMA_SERVER_LDAP=true
    ;;
  airgapped | --airgapped)
    AIRGAPPED=true
    ;;
  --pypi-webserver-port=*)
    PYPI_WEBSERVER_PORT=${args[i]#*=}
    ;;
  --pypi-webserver-port)
    PYPI_WEBSERVER_PORT="${args[i+1]}"
    skip_next=true
    ;;
  --cma-extras-gpl-tar-location=*)
    CMA_EXTRAS_GPL_TAR_LOCATION=${args[i]#*=}
    ;;
  --cma-extras-gpl-tar-location)
    CMA_EXTRAS_GPL_TAR_LOCATION="${args[i+1]}"
    skip_next=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_SERVER_START_TIMEOUT=${args[i]#*=}
    ;;
  --start-timeout)
    CMA_SERVER_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
    ;;
  --vault)
    CMA_VAULT=true
    ;;
  --vault-server-port=*)
    VAULT_SERVER_PORT=${args[i]#*=}
    ;;
  --vault-server-port)
    VAULT_SERVER_PORT="${args[i+1]}"
    skip_next=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
    ;;
  --db-pass=*)
    CMA_DBA_PASS=${args[i]#*=}
    ;;
  --db-pass)
    CMA_DBA_PASS="${args[i+1]}"
    skip_next=true
    ;;
  --auth-db-pass=*)
    CMA_AUTH_DBA_PASS=${args[i]#*=}
    ;;
  --auth-db-pass)
    CMA_AUTH_DBA_PASS="${args[i+1]}"
    skip_next=true
    ;;
  --client-secret=*)
    CMA_CLIENT_SECRET=${args[i]#*=}
    ;;
  --client-secret)
    CMA_CLIENT_SECRET="${args[i+1]}"
    skip_next=true
    ;;
  -h | --help)
    HELP=true
    ;;
  -v | --verbose)
    VERBOSE=true
    ;;
  *)
    if [ "${RUN_SSL_SETUP}" = false ]; then
      echo "Unknown option: ${args[i]}"
      HELP=true
    fi
    ;;
  esac
done

DEPRECATED_COMMANDS_MESSAGE="Actions starting with '--' are deprecated and will be removed in future releases"

__usage="
Usage: ${CMA_CLI_COMMAND:-$(basename "$0")} [actions] [options]
Available actions:
   start,     --start:  Start the CMA server
   stop,      --stop: Stop the CMA server
   restart,   --restart: Restart the CMA server
   rebuild,   --rebuild: Reinstall the CMA server
   ssl: Enable SSL setup
 **Note $DEPRECATED_COMMANDS_MESSAGE
Options:
   --ssl: Enable ssl for the CMA server (deprecated, will be removed in future releases, use 'ssl' action instead)
   -ad, --app-data-dir: Sets the folder where configs, logs and data are placed for instances (Default: ${CMA_APP_DATA_DIR}})
   -n,  --instance-name: Set the name of the instance (Default: ${CMA_INSTANCE_NAME})
   -p,  --profile: Set additional profile(s) for the cma-server
   -py, --python-executable: Path to python3 executable
        --airgapped: Turn on airgapped mode (meaning: install all pypi deps from cma & cma-extras artifact) (Default: $AIRGAPPED)
        --pypi-webserver-port: Port of local pypi webserver
        --cma-extras-gpl-tar-location: Location of GPL extras TAR (Default: ROOT_DIR/..) NOTE: this a requirement for airgapped mode!!
        --start-timeout: Set timeout for server start (Default: $DEFAULT_CMA_SERVER_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.
        --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 TLS is enabled)
        --db-pass: Database password (required; prompted interactively if omitted)
        --auth-db-pass: Auth server database password (prompted interactively if omitted; defaults to --db-pass if left empty)
        --client-secret: OAuth2 client secret shared by auth and gateway servers (required; prompted interactively if omitted; persisted across restarts)
   -v,  --verbose: Print verbose log
   -h,  --help: Print this help
"

if [ "${HELP}" = true ]; then
  if [ "${RUN_SSL_SETUP}" = true ]; then
    source "$SCRIPT_PATH"/common.sh # load commons
    if [ "${CMA_MASTER}" = true ]; then
      service_type="master"
    else
      service_type="server"
    fi
    run_ssl_setup "${service_type}" "local" "${args[@]}"
  else
    echo "$__usage"
  fi
  exit 0
fi

echo "WARNING: ${DEPRECATED_COMMANDS_MESSAGE}"

CMA_INSTANCE_DIR=${CMA_APP_DATA_DIR}/${CMA_INSTANCE_NAME}
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_PIP_INDEX_URL

source "$SCRIPT_PATH"/common.sh # load commons
CMA_DIST_TYPE=${CMA_DIST_TYPE:-distributed}
export CMA_DIST_TYPE

if [ "${CMA_DIST_TYPE}" = "distributed" ]; then
  source "$SCRIPT_PATH"/distributed-common.sh
fi

create_logs_dir
LOG_FILE="$LOGS_DIR"/$(basename "$0" .sh).log
CMA_EXTRAS_GPL_TAR_LOCATION=${CMA_EXTRAS_GPL_TAR_LOCATION:-$(ls "${ROOT_DIR}/.."/cma-extras-gpl-*.tar.gz 2>/dev/null | tail -n1)}

if [ -z "${ACTION_START}" ] && [ -z "${ACTION_STOP}" ] && [ -z "${ACTION_REBUILD}" ] && [ -z "${RUN_SSL_SETUP}" ]; then
  ACTION_START=true
fi

echo "#################################################################################################################" >>"$LOG_FILE"
echo "Actions: ACTION_START: ${ACTION_START:-false}, ACTION_STOP: ${ACTION_STOP:-false}, ACTION_REBUILD: ${ACTION_REBUILD:-false}, RUN_SSL_SETUP: ${RUN_SSL_SETUP:-false}" >>"$LOG_FILE"

if [ "${RUN_SSL_SETUP}" = true ]; then
  if [ "${CMA_MASTER}" = true ]; then
    echo "Running SSL setup for master CMA server"
    run_ssl_setup "master" "local" "${args[@]}"
  else
    echo "Running SSL setup for local CMA server"
    run_ssl_setup "server" "local" "${args[@]}"
  fi
  exit $?
fi

#CMA_SERVER_HOME_DIR="${ROOT_DIR}/cma-server"
CMA_SERVER_PID_DIR=${CMA_SERVER_PID_DIR:-${CMA_INSTANCE_DIR}}
CMA_SERVER_PID_FILE="${CMA_SERVER_PID_DIR}/cma-server.pid"
CMA_SERVER_LOG_FILE=${CMA_LOG_DIR}/cma-server.log

if [ -n "${CMA_SERVER_CONF_FILE}" ]; then
  if [ -f "${CMA_SERVER_CONF_FILE}" ]; then

    echo "Loading cma-server-conf file (${CMA_SERVER_CONF_FILE})"

    if [ -z "${CMA_SERVER_SSL}" ]; then
      if is_ssl_active; then
        CMA_SERVER_SSL=true
      fi
    fi
    if [ -z "${CMA_VAULT}" ]; then
      if is_vault_active; then
        CMA_VAULT=true
      fi
    fi

    if [ -z "${CMA_SERVER_EXTRA_PROFILE}" ]; then
      CMA_SERVER_EXTRA_PROFILE=$(get_extra_profiles)
    fi
  fi
fi

if [ -n "${CMA_SSL_CONF_FILE}" ] && [ -f "${CMA_SSL_CONF_FILE}" ]; then

  echo "Loading cma-ssl file (${CMA_SSL_CONF_FILE})"
  if [ -z "${CMA_SERVER_SSL}" ]; then
    if is_ssl_active; then
      CMA_SERVER_SSL=true
    fi
  fi
fi

CMA_SERVER_SSL=${CMA_SERVER_SSL:-false}

echo "SSL configured: ${CMA_SERVER_SSL:-false}" | tee -a "$LOG_FILE"
echo "Vault configured: ${CMA_VAULT:-false}" | tee -a "$LOG_FILE"
echo "Airgapped configured: ${AIRGAPPED:-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

load_PYTHON_EXECUTABLE_variable() {
  if [ -z "${PYTHON_EXECUTABLE}" ]; then
    PYTHON_EXECUTABLE=$(get_python_executable)
  fi
}

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

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

cleanup() {
  echo -e '\n'
  if [ "${SETUP_CMA_SERVER}" = 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
}

stop_cma_server() {
  if is_cma_server_running; then
    export CMA_SERVER_ENV_FILE
    echo -n "Stopping the CMA server.." | tee -a "$LOG_FILE"
    execute_command "$ROOT_DIR"/cma-server/cma-server.sh --stop --cma-server-conf="${CMA_SERVER_CONF_FILE}"

    # check if cma_server stopped
    wait_for_cma_server_to_stop $CMA_SERVER_LOG_FILE $CMA_SERVER_STOP_TIMEOUT

    if [ "$AIRGAPPED" = true ]; then
      "$SCRIPT_PATH"/pypi-server.sh --stop
      if [ $? -ne 0 ]; then
        echo "Failed to stop the pypi server!"
        exit 1
      fi
    fi
  else
    echo "CMA server is not running!"
  fi
}

start_cma_server() {
  # create cma-server.properties file
  if [ ! -f "${CMA_SERVER_CONF_FILE}" ]; then
    read_cma_ssl_conf
    configure_db_type
    create_master_db_conf
    create_auth_db_conf
    create_cma_server_conf
    if [ -n "${SSL_PROFILE}" ]; then
      add_to_active_profiles "${SSL_PROFILE}" "cma.server.profiles"
    fi
  else
    # update profiles
    local old_server_profiles=$(get_cma_conf_value "cma.server.profiles")
    local new_server_profiles=$(get_server_profiles)
    if [ "${old_server_profiles}" != ${new_server_profiles} ]; then
      set_cma_conf_value "cma.server.profiles" "${new_server_profiles}"
      echo "Changed server profile from ${old_server_profiles} to ${new_server_profiles} " | tee -a "$LOG_FILE"
    fi
  fi

  if [ "$AIRGAPPED" = true ]; then
    load_PYTHON_EXECUTABLE_variable

    # create cma-vault-server.properties file
    if [ ! -f "${CMA_PYPI_SERVER_CONF_FILE}" ]; then
      create_cma_pypi_server_conf
    fi

    echo "Starting the PyPi server.."
    "$SCRIPT_PATH"/pypi-server.sh --start -py="${PYTHON_EXECUTABLE}" -n="${CMA_INSTANCE_NAME}" -psc="${CMA_PYPI_SERVER_CONF_FILE}"
    if [ $? -ne 0 ]; then
      echo "Failed to start the PyPi server!" | tee -a "$LOG_FILE"
      exit 1
    fi
  fi
  if [ "${CMA_VAULT}" = true ]; then
    load_PYTHON_EXECUTABLE_variable
    ensure_vault_authentication "local"
  fi
  if ! is_cma_server_running; then

    if [ "$CMA_SKIP_PORT_CHECK" = true ]; then
      echo "Port(s) verification skipped!" | tee -a "$LOG_FILE"
    else
      verify_cma_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-server.sh
    fi

    # check if DB backup/restore is required
    backup_or_restore_cma_db_if_version_changed

    # create cma-server.env
    if [ ! -f ${CMA_SERVER_ENV_FILE} ]; then
      create_cma_server_env
    else
      if [ -n "${CMA_VERSION}" ] && [ "${CMA_VERSION}" != '' ]; then
        echo "update cma version to ${CMA_VERSION}" | tee -a "$LOG_FILE"
        set_cma_environment_variable_value "CMA_VERSION" ${CMA_VERSION}
      fi

      if [ -n "${CMA_UPGRADE_FROM}" ]; then
        set_cma_environment_variable_value "CMA_UPGRADE_FROM" ${CMA_UPGRADE_FROM}
      fi

      # set instance name if missing
      if [ -z $(get_cma_environment_variable_value "CMA_INSTANCE_NAME") ] && [ -n "${CMA_INSTANCE_NAME}" ]; then
        set_cma_environment_variable_value "CMA_INSTANCE_NAME" ${CMA_INSTANCE_NAME}
      fi
    fi

    CMA_SERVER_OPTS="--start --am2cm-root-dir=${ROOT_DIR} --cma-server-conf=${CMA_SERVER_CONF_FILE} "
    if [ "$AIRGAPPED" = true ]; then
      CMA_SERVER_OPTS+="--airgapped --cma-pypi-server-conf=${CMA_PYPI_SERVER_CONF_FILE} "
    fi
    if [ "$CMA_SKIP_JAVA_CHECK" = true ]; then
      CMA_SERVER_OPTS+="--skip-java-check "
    fi
    if [ "$CMA_SKIP_SSL_CHECK" = true ]; then
      CMA_SERVER_OPTS+="--skip-ssl-check "
    fi
    if [ "$CMA_SKIP_PORT_CHECK" = true ]; then
      CMA_SERVER_OPTS+="--skip-port-check "
    fi
    if [ "${CMA_VAULT}" = true ]; then
      CMA_SERVER_OPTS+="--cma-vault-server-conf=${CMA_VAULT_SERVER_CONF_FILE} "
    fi

    export CMA_SERVER_ENV_FILE

    umask 027

    ensure_internal_keystore_password "${CMA_CONF_DIR}"
    ensure_grpc_keystore "${CMA_CONF_DIR}"

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

    execute_command "$ROOT_DIR"/cma-server/cma-server.sh ${CMA_SERVER_OPTS}

    # check if cma_server started
    wait_for_cma_server_to_start $CMA_SERVER_LOG_FILE $CMA_SERVER_START_TIMEOUT

    CMA_SERVER_PROTOCOL=$(get_cma_server_protocol)
    if [ "${CMA_DIST_TYPE}" = "distributed" ]; then
      echo "The cma-gateway-server is available at ${CMA_SERVER_PROTOCOL}://${CMA_GATEWAY_SERVER_HOST}:${CMA_GATEWAY_SERVER_PORT} " | tee -a "$LOG_FILE"
    else
      if [ -z "${CMA_SERVER_PORT}" ]; then
          CMA_SERVER_PORT=$(get_cma_server_port)
      fi
      echo "The cma-server is available at ${CMA_SERVER_PROTOCOL}://localhost:${CMA_SERVER_PORT} " | tee -a "$LOG_FILE"
    fi
  else
    echo "CMA server is running!"
  fi
}

# deprecated function, this will be removed when master-agent becomes the default
setup_cma() {
  if is_dev_tty_available; then
    echo -n "Setting up the CMA server.." | tee -a "$LOG_FILE"
  else
    echo "Setting up the CMA server.." | tee -a "$LOG_FILE"
  fi
  execute_command "$SCRIPT_PATH"/cma-agent.sh setup
  echo "Done!" | tee -a "$LOG_FILE"
}

# deprecated function, this will be removed when master-agent becomes the default
reinstall() {
    # stop cma-server if running
    if is_cma_server_running; then
      stop_cma_server
    fi

    setup_cma
}

if [ "${ACTION_STOP}" = true ]; then
  stop_cma_server
  if [ "${CMA_DIST_TYPE}" = "distributed" ]; then
    if [ "${VERBOSE}" != true ]; then
      export LOG_FILE
      export -f is_process_from_pidfile_running
    fi
    if is_dev_tty_available; then
      echo -n "Stopping the Gateway Server.." | tee -a "$LOG_FILE"
    else
      echo "Stopping the Gateway Server.." | tee -a "$LOG_FILE"
    fi
    execute_command stop_cma_gateway_server
    echo "Done!" | tee -a "$LOG_FILE"

    if is_dev_tty_available; then
      echo -n "Stopping the Auth Server.." | tee -a "$LOG_FILE"
    else
      echo "Stopping the Auth Server.." | tee -a "$LOG_FILE"
    fi
    execute_command stop_cma_auth_server
    echo "Done!" | tee -a "$LOG_FILE"
  fi
fi


if [ "${ACTION_REBUILD}" = true ]; then
  if [ "${CMA_MASTER}" = true ]; then
    echo "Rebuild is not supported for master mode!" | tee -a "$LOG_FILE"
    exit 1
  fi
  reinstall
fi

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

    # --- LOAD ---
    load_master_db_conf
    load_auth_db_conf
    load_master_auth_conf
    load_cma_agent_auth_conf

    # --- LOGIC ---
    prompt_for_master_secrets
    export CMA_CLIENT_SECRET
    read_cma_ssl_conf
    configure_db_type
    ensure_internal_keystore_password "${CMA_CONF_DIR}"
    ensure_grpc_keystore "${CMA_CONF_DIR}"

    # --- CREATE ---
    create_master_auth_conf
    create_master_db_conf
    create_auth_db_conf
    create_cma_agent_auth_conf
    create_cma_server_conf
    if [ -n "${SSL_PROFILE}" ]; then
      add_to_active_profiles "${SSL_PROFILE}" "cma.server.profiles"
    fi

    if is_dev_tty_available; then
      echo -n "Starting the Auth Server.." | tee -a "$LOG_FILE"
    else
      echo "Starting the Auth Server.." | tee -a "$LOG_FILE"
    fi
    execute_command start_cma_auth_server
    echo "Done!" | tee -a "$LOG_FILE"

    wait_for_auth_server_running

    if is_dev_tty_available; then
      echo -n "Starting the Gateway Server.." | tee -a "$LOG_FILE"
    else
      echo "Starting the Gateway Server.." | tee -a "$LOG_FILE"
    fi
    execute_command start_cma_gateway_server
    echo "Done!" | tee -a "$LOG_FILE"
  fi
  start_cma_server
fi
