#
# 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_INSTANCE_NAME=${CMA_INSTANCE_NAME:-cma-server}
CMA_APP_DATA_DIR=${CMA_APP_DATA_DIR:-${HOME}/.cma}

while [[ $# -gt 0 ]]; do
  case $1 in
  start | --start)
    ACTION_START=true
    shift # past argument with no value
    ;;
  stop | --stop)
    ACTION_STOP=true
    shift # past argument with no value
    ;;
  restart | --restart)
    ACTION_STOP=true
    ACTION_START=true
    shift # past argument with no value
    ;;
  -n=* | --instance-name=*)
    CMA_INSTANCE_NAME=${1#*=}
    shift # past argument=value
    ;;
  -n | --instance-name)
    CMA_INSTANCE_NAME=$2
    shift # past argument
    shift # past value
    ;;
  -py | --python-executable)
    PYTHON_EXECUTABLE=$2
    shift # past argument
    shift # past value
    ;;
  -py=* | --python-executable=*)
    PYTHON_EXECUTABLE=${1#*=}
    shift # past argument=value
    ;;
  -psc | --cma-pypi-server-conf)
    CMA_PYPI_SERVER_CONF_FILE=$2
    shift # past argument
    shift # past value
    ;;
  -psc=* | --cma-pypi-server-conf=*)
    CMA_PYPI_SERVER_CONF_FILE=${1#*=}
    shift # past argument=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:
    --start: Start the PyPi server
    --stop: Stop the PyPi server
    -n,  --instance-name <name>: Set the name of the instance (Default: ${CMA_INSTANCE_NAME})
    -py, --python-executable <path>: Path to python3 executable
    -psc, --cma-pypi-server-conf: The config file of the cma-pypi-server (Default: ${CMA_APP_DATA_DIR}/${CMA_INSTANCE_NAME}/cma-pypi-server.properties)
    -h, --help: Print this help
 "

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

CMA_INSTANCE_DIR=${CMA_APP_DATA_DIR}/${CMA_INSTANCE_NAME}
CMA_CONF_DIR=${CMA_CONF_DIR:-${CMA_INSTANCE_DIR}/conf}

# check if CMA running in docker mode
if [ -f "${CMA_CONF_DIR}/cma-docker.env" -a "${DOCKER_MODE}" != true ]; then
  container_id=$(get_cma_environment_variable_value "LAST_DOCKER_CONTAINER_ID" "${CMA_CONF_DIR}/cma-docker.env" )
  echo "The CMA is configured in docker mode! This script '${CMA_CLI_COMMAND:-$(basename "$0")}' should be used inside the container ${container_id}"
  exit 1
fi

# reload existing cma-pypi-server-conf file if it exists and is not specified
if [ -z "${CMA_PYPI_SERVER_CONF_FILE}" ]; then
  # checking default property file in cma conf dir
  DEFAULT_CMA_PYPI_SERVER_CONF_FILE="${CMA_CONF_DIR}/cma-pypi-server.properties"
  if [ -f "${DEFAULT_CMA_PYPI_SERVER_CONF_FILE}" ]; then
    echo "Since the cma-pypi-server-conf file is not specified, it uses the one in the ${CMA_CONF_DIR} folder."
    CMA_PYPI_SERVER_CONF_FILE="${DEFAULT_CMA_PYPI_SERVER_CONF_FILE}"
  else
    echo "No cma-pypi-server-conf file found in the ${CMA_CONF_DIR} folder."
  fi
fi

# source utils
source "${SCRIPT_PATH}"/utils.sh

if [ -n "${CMA_PYPI_SERVER_CONF_FILE}" ]; then

  if [ ! -f "${CMA_PYPI_SERVER_CONF_FILE}" ]; then
    echo "Could not open ${CMA_PYPI_SERVER_CONF_FILE}!"
    exit 1
  fi

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

  if [ -z "${PYPI_WEBSERVER_PORT}" ]; then
    PYPI_WEBSERVER_PORT=$(get_cma_conf_value "cma.pypi.server.port" ${CMA_PYPI_SERVER_CONF_FILE})
  fi
fi


source "$SCRIPT_PATH"/common.sh # load commons
create_logs_dir

LOG_FILE="$LOGS_DIR"/$(basename "$0" .sh).log

start_pypi_server() {

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

  if [ ! -f "${CMA_PYPI_SERVER_CONF_FILE}" ]; then
    create_cma_pypi_server_conf
  fi

  stop_pypi_server
  echo "Starting Local PyPi server! py=${PYTHON_EXECUTABLE}, port:${PYPI_WEBSERVER_PORT}"
  "${PYTHON_EXECUTABLE}" -m http.server "${PYPI_WEBSERVER_PORT}" --directory "$ROOT_DIR"/cma-ansible/cma-setup/python_dependencies  2>&1 > "$LOGS_DIR/local_pypi_server.log" &
  echo $! > "$PYPI_SERVER_PID_FILE"
  if ! is_pypi_server_running; then
    echo "Failed to start Local PyPi server - Exiting..." | tee -a "$LOG_FILE"
    exit 1
  fi
  echo "Started Local PyPi server! Logging into $LOGS_DIR/local_pypi_server.log" | tee -a "$LOG_FILE"
}

stop_pypi_server() {
  echo "Stopping Local PyPi server"
  if is_pypi_server_running; then
    local pypi_pid=$(get_pypi_server_pid)
    kill "$pypi_pid"
    if [ "$?" -eq 0 ]; then
      rm $PYPI_SERVER_PID_FILE
    else
      echo "Failed to stop Local PyPi server - Exiting..." | tee -a "$LOG_FILE"
      exit 1
    fi
  fi
}

cleanup_pypi_server () {  # this method is expected to be called only from a trap on EXIT
  if [ "$?" -ne 0 ]; then
    stop_pypi_server
  fi
}

trap "cleanup_pypi_server" EXIT

if [ "${ACTION_STOP}" = true ]; then
  stop_pypi_server
fi

if [ "${ACTION_START}" = true ]; then
  start_pypi_server
fi
