#!/usr/bin/env bash
#
# Copyright (c) 2024, 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_BIN_DIR=${CMA_BIN_DIR:-$SCRIPT_PATH}
CMA_HOME=${CMA_HOME:-${CMA_BIN_DIR}/..}
VAULT_SERVER_BIN_DIR="$CMA_HOME/vault-local/scripts/bin"

__usage="
Usage: $(basename "$0") [command]
Available commands:
   local:  Launch CMA locally (standalone)
   docker: Launch CMA in a docker container
   master:  Managing the CMA Master instance
   agent:  Managing the CMA Agent instance
   configure: Configure ports, etc. for CMA
   ssl: Configure ssl for CMA
   vault: Launch Vault server
   pypi: Launch PyPi server
   help: Print this help
 "

# deprecated function, this will be removed when master-agent becomes the default
cma__local() {
  command ${CMA_BIN_DIR}/cma-local.sh "$@"
  return $?
}

# deprecated function, this will be removed when master-agent becomes the default
cma__docker() {
  command ${CMA_BIN_DIR}/cma-docker.sh "$@"
  return $?
}

cma__ssl() {
  command ${CMA_BIN_DIR}/setup-ssl.sh "$@"
  return $?
}

cma__configure() {
  command ${CMA_BIN_DIR}/configure.sh "$@"
  return $?
}

cma__vault() {
  command ${VAULT_SERVER_BIN_DIR}/vault-server.sh "$@"
  return $?
}

cma__pypi() {
  command ${CMA_BIN_DIR}/pypi-server.sh "$@"
  return $?
}

cma__agent() {
  command ${CMA_BIN_DIR}/cma-agent.sh "$@"
  return $?
}

cma__master() {
  command ${CMA_BIN_DIR}/cma-master.sh "$@"
  return $?
}

cma__help() {
  echo "$__usage"
  exit 0
}

cma() {
  if [ "$#" -eq 0 ] || [ "$1" = '-h' ] || [ "$1" = '--help' ]; then cma__help; fi

  local subcommand=${1//-/_};
  if declare -f "cma__$subcommand" >/dev/null 2>&1; then
    [ "$#" -gt 0 ] && shift
    export CMA_CLI_COMMAND="cma $subcommand"
    "cma__$subcommand" "$@"
    ret=$?
    unset CMA_CLI_COMMAND
  else
    cma__local "$@" # call the local by default
    ret=$?
  fi
  exit $ret
}

# if called as source code, you can just call "cma local" or "cma docker"
# return if called as source code, otherwise call cma function with args
[[ $_ != $0 ]] && return 2>/dev/null

cma "$@"
