#!/usr/bin/env bash
#
# Copyright (c) 2024-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.
#

DEFAULT_CMA_INSTANCE_NAME=cma-server
DEFAULT_CMA_SERVER_HTTP_PORT=8090
DEFAULT_CMA_SERVER_HTTPS_PORT=8093
DEFAULT_CMA_PYPI_WEBSERVER_PORT=9003
DEFAULT_VAULT_SERVER_PORT=8210
DEFAULT_VAULT_SERVER_VERSION=1.14.8

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

CMA_INSTANCE_NAME=${CMA_INSTANCE_NAME:-${DEFAULT_CMA_INSTANCE_NAME}}
CMA_APP_DATA_DIR=${CMA_APP_DATA_DIR:-${HOME}/.cma}

#
# Update the specified config in the cma-server.env file
#
# $1 env nane
# $2 env value
# $3 config file, default ${CMA_SERVER_CONF_FILE}
update_config() {
  local conf_name=$1
  local new_value=$2
  local conf_file=${3:-${CMA_SERVER_CONF_FILE}}

  env_value=$(get_cma_conf_value "${conf_name}" "${conf_file}")
  if [ "${env_value}" != "${new_value}" ]; then
    echo "Set ${conf_name} to ${new_value}"
    set_cma_conf_value "${conf_name}" "${new_value}" "${conf_file}"
    return 0
  fi
  return 1
}

# $1: env name
# $2: port
# $3: config file, default ${CMA_SERVER_CONF_FILE}
update_port() {
  local conf_name=$1
  local port=$2
  local conf_file=${3:-${CMA_SERVER_CONF_FILE}}
  local pid=${4:-$(get_cma_server_pid)}

  # check if port is not in use
  if ! verify_port "${port}" "${pid}"; then
    echo "$conf_name is not set because port $port is used by another process!"
    return 1
  fi
  update_config "${conf_name}" "${port}" "${conf_file}"
  return $?
}

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

while [[ $# -gt 0 ]]; do
  case $1 in
  -n=* | --instance-name=*)
    CMA_INSTANCE_NAME=${1#*=}
    shift # past argument=value
    ;;
  -n | --instance-name)
    CMA_INSTANCE_NAME=$2
    shift # past argument
    shift # past value
    ;;
  -p=* | --server-port=*)
    IN_CMA_SERVER_HTTP_PORT=${1#*=}
    shift # past argument=value
    ;;
  -p | --server-port)
    IN_CMA_SERVER_HTTP_PORT=$2
    shift # past argument
    shift # past value
    ;;
  -P=* | --server-https-port=*)
    IN_CMA_SERVER_HTTPS_PORT=${1#*=}
    shift # past argument=value
    ;;
  -P | --server-https-port)
    IN_CMA_SERVER_HTTPS_PORT=$2
    shift # past argument
    shift # past value
    ;;
  -ppp=* | --pypi-webserver-port=*)
    IN_CMA_PYPI_WEBSERVER_PORT=${1#*=}
    shift # past argument=value
    ;;
  -ppp | --pypi-webserver-port)
    IN_CMA_PYPI_WEBSERVER_PORT=$2
    shift # past argument
    shift # past value
    ;;
  -vp=* | --vault-server-port=*)
    IN_VAULT_SERVER_PORT=${1#*=}
    shift # past argument=value
    ;;
  -vp | --vault-server-port)
    IN_VAULT_SERVER_PORT=$2
    shift # past argument
    shift # past value
    ;;
  -vv=* | --vault-server-version=*)
    IN_VAULT_SERVER_VERSION=${1#*=}
    shift # past argument=value
    ;;
  -vv | --vault-server-version)
    IN_VAULT_SERVER_VERSION=$2
    shift # past argument
    shift # past value
    ;;
  -h | --help)
    HELP=true
    shift # past argument with no value
    ;;
  *)
    echo "Unknown option: $1"
    HELP=true
    shift # past argument with no value
    ;;
  esac
done

__usage="
Usage: ${CMA_CLI_COMMAND:-$(basename "$0")} [options]
Options:
  -n,   --instance-name <name>: Set the name of the instance (Default: ${DEFAULT_CMA_INSTANCE_NAME})
  -p,   --server-port <arg>: Set the http port for the CMA server (Default: ${DEFAULT_CMA_SERVER_HTTP_PORT})
  -P,   --server-https-port <arg>: Set the https port for the CMA server (Default: ${DEFAULT_CMA_SERVER_HTTPS_PORT})
  -ppp, --pypi-webserver-port <arg>: Port of local pypi webserver for airgapped mode (Default: ${DEFAULT_CMA_PYPI_WEBSERVER_PORT})
  -vp,  --vault-server-port <arg>: Port of local vault server (Default: ${DEFAULT_VAULT_SERVER_PORT})
  -vv,  --vault-server-version <arg>: Version of local vault server (Default: ${DEFAULT_VAULT_SERVER_VERSION})
  -h,   --help: Print this help
"

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

if [ "${HELP}" = true ]; then
  print_help
fi

CMA_INSTANCE_DIR=${CMA_APP_DATA_DIR}/${CMA_INSTANCE_NAME}
CMA_CONF_DIR=${CMA_CONF_DIR:-${CMA_INSTANCE_DIR}/conf}
CMA_DATA_DIR=${CMA_DATA_DIR:-${CMA_INSTANCE_DIR}/data}
CMA_LOG_DIR=${CMA_LOG_DIR:-${CMA_INSTANCE_DIR}/logs}

if [ -n "${IN_CMA_SERVER_HTTP_PORT}" ]; then
  CMA_SERVER_HTTP_PORT=${IN_CMA_SERVER_HTTP_PORT}
fi
if [ -n "${IN_CMA_SERVER_HTTPS_PORT}" ]; then
  CMA_SERVER_HTTPS_PORT=${IN_CMA_SERVER_HTTPS_PORT}
fi
if [ -n "${IN_CMA_PYPI_WEBSERVER_PORT}" ]; then
  CMA_PYPI_WEBSERVER_PORT=${IN_CMA_PYPI_WEBSERVER_PORT}
fi
if [ -n "${IN_VAULT_SERVER_PORT}" ]; then
  VAULT_SERVER_PORT=${IN_VAULT_SERVER_PORT}
fi

if [ -n "${IN_VAULT_SERVER_VERSION}" ]; then
  VAULT_SERVER_VERSION=${IN_VAULT_SERVER_VERSION}
fi

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

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

# create cma-server.properties
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

  if [ -n "${CMA_DBA_PASS}" ]; then
    create_master_db_conf
    create_auth_db_conf
  fi
else
  backup_cma_server_conf

  changed=false
  if [ -n "${IN_CMA_SERVER_HTTP_PORT}" ]; then
    update_port "cma.server.http.port" "${CMA_SERVER_HTTP_PORT}"  | tee -a "$LOG_FILE"
    if [ ${PIPESTATUS[0]} -eq 0 ]; then
      changed=true
    fi
  fi

  if [ -n "${IN_CMA_SERVER_HTTPS_PORT}" ]; then
    update_port "cma.server.https.port" "${CMA_SERVER_HTTPS_PORT}"  | tee -a "$LOG_FILE"
    if [ ${PIPESTATUS[0]} -eq 0 ]; then
      changed=true
    fi
  fi

  if [ "$changed" = true ]; then
    echo "The change(s) will take effect after the CMA server is restarted!"
  else
    echo "Nothing is changed";
  fi
fi

# create cma-pypi-server.properties
if [ ! -f ${CMA_PYPI_SERVER_CONF_FILE} ]; then
  create_cma_pypi_server_conf
else
  backup_cma_pypi_server_conf

  changed=false
  if [ -n "${IN_CMA_PYPI_WEBSERVER_PORT}" ]; then
    update_port "cma.pypi.server.port" "${PYPI_WEBSERVER_PORT}" "${CMA_PYPI_SERVER_CONF_FILE}" $(get_pypi_server_pid)  | tee -a "$LOG_FILE"
    if [ ${PIPESTATUS[0]} -eq 0 ]; then
      changed=true
    fi
  fi

  if [ "$changed" = true ]; then
    echo "The change(s) will take effect after both CMA and PyPi Server are restarted!"
  else
    echo "Nothing is changed";
  fi
fi