#!/usr/bin/env sh

set -ox errexit
if [ -z "${POD_NAME}" ]; then
    echo "Environment variable POD_NAME not found..."
    env
    exit
fi

# This script checks for a maintenance lock file and pauses the container's
# startup if the current pod is marked for maintenance.
# It is designed to handle SIGTERM gracefully to allow for clean pod deletion.
#
# It expects the following environment variables to be set:
#   - POD_NAME: The name of the current pod (e.g., from the Downward API).

# This function is called by the trap command when a signal is received.
handle_exit() {
    echo
    echo "===> Termination signal received. Cleaning up sleep process..."
    # The 'kill' command will terminate the background 'sleep' process.
    if [ -n "$SLEEP_PID" ]; then
        kill "$SLEEP_PID"
    fi
    echo "===> Exiting gracefully."
    exit 0
}

# --- Main Maintenance Check Function ---

# Check for maintenance mode configuration
checkMaintenanceMode() {
    # Using the path you specified.
    local maintenance_config="/mnt/config/init/maintenance_mode.config"

    if [ -f "${maintenance_config}" ]; then
        echo "===> Checking maintenance mode configuration..."

        # Check if current pod is in maintenance mode
        if jq -e --arg pod_name "${POD_NAME}" 'has($pod_name)' "${maintenance_config}" > /dev/null 2>&1; then
            local mode
            mode=$(jq -r --arg pod_name "${POD_NAME}" '.[$pod_name].mode' "${maintenance_config}")
            if [ "${mode}" = "MAINTENANCE" ]; then
                echo "===> Pod ${POD_NAME} is in MAINTENANCE mode. Pausing gracefully to allow for manual repair."
                echo "===> Send SIGTERM (e.g., 'kubectl delete pod') to exit."

                # Set the trap to call our handle_exit function on SIGTERM or SIGINT.
                trap handle_exit SIGTERM SIGINT

                # Run sleep in the background.
                sleep infinity &

                # Store its Process ID.
                SLEEP_PID=$!

                # Wait for the sleep process. The 'wait' command allows the
                # script to be interrupted by the trap and pause here.
                wait "$SLEEP_PID"
            fi
        fi
    fi

    # If the pod was not in maintenance, the script continues and exits here.
    echo "===> Pod is not in maintenance mode. Proceeding with normal startup."
}

################################################################################
# CRITICAL: DO NOT ADD CODE ABOVE THIS LINE
################################################################################
# The following `checkMaintenanceMode` function MUST be the first substantive
# action in this script. This ensures that the pod can be correctly paused for
# manual repair before any other initialization logic runs. Adding code above
# this point could interfere with the startup sequence in a critical recovery
# scenario.
################################################################################

# Check maintenance mode before proceeding
checkMaintenanceMode

pod_name=${POD_NAME}
id=${pod_name##*-};
component_name=${POD_NAME%-*}

if [ -e "/mnt/config/pod/${component_name}/template.jsonnet" ]; then
  cat < /mnt/config/pod/"${component_name}"/template.jsonnet | base64 -d > /opt/template.jsonnet
  /usr/local/bin/jsonnet /opt/template.jsonnet --ext-str id="${id}" -o /opt/"${component_name}".json
  cat /opt/"${component_name}".json
  /opt/parser.py "${component_name}" "/opt/${component_name}.json" /mnt/config
elif [ -e "/mnt/config/init/template.jsonnet" ]; then
  # new version of operator 2.0
  cat < /mnt/config/init/template.jsonnet | base64 -d > /mnt/config/template.jsonnet
  cat < /mnt/config/init/data.json | base64 -d > /mnt/config/data.json
  /opt/config.py "${pod_name}" /mnt/config/data.json /mnt/config/template.jsonnet /mnt/config/"${component_name}".json
  cat /mnt/config/"${component_name}".json
  /opt/parser.py "${component_name}" /mnt/config/"${component_name}".json /mnt/config
  # write to both locations to support image overrides
  mkdir -p /mnt/config/pod/"${pod_name}"
  /opt/parser.py "${component_name}" /mnt/config/"${component_name}".json /mnt/config/pod/"${pod_name}"
  # clean up excess output files
  rm /mnt/config/template.jsonnet /mnt/config/data.json /mnt/config/"${component_name}".json

  if [ "${OPERATOR_CP_TYPE}" = "connect" ] && [ -e "/mnt/config/shared/plugins.json" ]; then
    cat < /mnt/config/shared/plugins.json | base64 -d > /mnt/config/plugins.json
    /opt/generate_install_plugin_script.py /mnt/config/plugins.json /mnt/config/install_plugins.sh
    cat /mnt/config/install_plugins.sh
    echo "===> Installing connector plugins"
    /mnt/config/install_plugins.sh
    rm /mnt/config/install_plugins.sh /mnt/config/plugins.json
  fi
else
  echo "template.jsonnet not found in the path"
  exit 1
fi

# load scripts accordingly.
# The injected env variable OPERATOR_CP_TYPE and CP_COMPONENT_NAME needs to match for the below logic to work.
if [ -n "${OPERATOR_CP_TYPE}" ]; then
  echo "load script for CP type: ${OPERATOR_CP_TYPE}"
  cp -r /opt/confluentinc/"${OPERATOR_CP_TYPE}"/ /mnt/config/
  echo "copy fips jvm config security files"
  cp -r /opt/confluentinc/fips/ /mnt/config/

  if [ "${OPERATOR_CP_TYPE}" = "kafka" ]; then
    cp /opt/confluentinc/filewatcher /mnt/config
  fi
fi
