#!/usr/bin/env bash
#
# Copyright 2020 Confluent Inc.
#
set -o nounset
set -o errexit

export CP_COMPONENT_NAME=kafka
export CP_COMPONENT_SCRIPT_DIR=/opt/confluentinc/etc/${CP_COMPONENT_NAME}
export KAFKA_CONFIG_DIR=/mnt/config

dynamic_configs_enabled=0
# verify if dynamic configs are enabled.
if [ $# -ge 1 ] && [ "$1" == "true" ]; then
  echo "Dynamic configs enabled for ${CP_COMPONENT_NAME}"
  dynamic_configs_enabled=1
fi

kraft_enabled=0
# verify if kraft is enabled.
if [ $# -ge 2 ] && [ "$2" == "true" ]; then
  echo "KRaft enabled for ${CP_COMPONENT_NAME}"
  # if this file is present, it means storage is formatted and we don't
  # need to format again
  export KRAFT_META_PROPS_FILE=/mnt/data/data0/logs/meta.properties
  kraft_enabled=1
fi

format_cluster_metadata_enabled=0
# verify if format cluster metadata is enabled.
if [ $# -ge 3 ] && [ "$3" == "true" ]; then
  echo "Dynamic configs enabled for ${CP_COMPONENT_NAME}"
  format_cluster_metadata_enabled=1
fi

echo "===> User: $(id)"
export OPERATOR_SCRIPT_DIR=/mnt/config/${CP_COMPONENT_NAME}
echo "===> Load ${CP_COMPONENT_NAME} operator scripts from path ${OPERATOR_SCRIPT_DIR}/bin"

"${OPERATOR_SCRIPT_DIR}"/bin/configure "$dynamic_configs_enabled" "$kraft_enabled" "$format_cluster_metadata_enabled"

# Run preflight migration check on KRaft controller pods during initial migration setup.
# The preflight runs when the operator propagates a migration ID into the shared ConfigMap.
# Customers opt in by adding the enable-preflight annotation on the KMJ CR.
if echo "${POD_NAME:-}" | grep -q "kraftcontroller"; then
  MIGRATION_ID=$(cat "/mnt/config/shared/preflight-migration-id" 2>/dev/null || echo "")
  if [ -n "$MIGRATION_ID" ]; then
    if ! command -v kafka-migration-check &>/dev/null; then
      echo "===> WARN: kafka-migration-check binary not found. Skipping preflight check."
    else
      PREFLIGHT_CONFIG="${CP_COMPONENT_SCRIPT_DIR}/${CP_COMPONENT_NAME}.properties"
      PREFLIGHT_MARKER="/mnt/data/data0/.preflight-done-${MIGRATION_ID}"
      if [ ! -f "$PREFLIGHT_MARKER" ]; then
        echo "===> Running KRaft migration preflight check"
        if ! kafka-migration-check preflight-check --controller-config "$PREFLIGHT_CONFIG"; then
          echo "===> ERROR: Preflight check failed. Blocking KRaft controller startup."
          echo "===> Review the preflight output above and fix the reported issues (recommended)."
          echo "===> If this is a false positive, remove the 'platform.confluent.io/kraft-migration-enable-preflight' annotation from the KRaftMigrationJob CR to disable the preflight check."
          exit 1
        fi
        touch "$PREFLIGHT_MARKER"
        echo "===> Preflight check complete."
      fi
    fi
  fi
fi

exec "${OPERATOR_SCRIPT_DIR}"/bin/launch "$dynamic_configs_enabled"
