#!/usr/bin/env bash
#
# Shared utility for resolving ${file:path:key} references in Jolokia config strings.
# Jolokia is a plain JVM agent that cannot resolve Kafka's FileConfigProvider syntax
# natively. This function reads the referenced file at pod runtime and substitutes
# the token with the actual value.
#
# Note: Truststore password resolution is not needed for Jolokia because it inherits
# the JVM-wide truststore configuration from JMX settings (-Djavax.net.ssl.trustStore).
#
# Usage:
#   source /mnt/config/resolve-file-refs.sh
#   resolved="$(resolve_file_password "$config_string")"
#

resolve_file_password() {
  local config="$1"

  # Resolve keystorePassword for Jolokia server certificate
  if [[ "$config" =~ keystorePassword=\$\{file:([^:]+):([^}]+)\} ]]; then
    local pwd_file="${BASH_REMATCH[1]}"
    local pwd_key="${BASH_REMATCH[2]}"
    local token="\${file:${pwd_file}:${pwd_key}}"

    local default_password="mystorepassword"

    if [ ! -e "$pwd_file" ]; then
      # Password file doesn't exist - fall back to default password
      # This can happen when directoryPathInContainer is set but jksPassword.txt is not injected
      config="${config//${token}/${default_password}}"
      echo "WARN: Password file '${pwd_file}' not found, using default password" >&2
    else
      # Password file exists - it MUST be valid (fail-fast if malformed)
      local pwd_line
      pwd_line="$(grep "^${pwd_key}=" "$pwd_file" 2>/dev/null | head -1)"

      if [ -z "$pwd_line" ]; then
        # Key not found in file - FAIL FAST (file exists but is malformed)
        echo "ERROR: Key '${pwd_key}' not found in '${pwd_file}'. File exists but is malformed. Expected format: ${pwd_key}=<password>" >&2
        exit 1
      fi

      # Extract password value (everything after first '=')
      # Command substitution $(...) automatically strips trailing newlines
      local pwd_value="${pwd_line#*=}"

      # Remove any trailing carriage return (Windows-style line endings)
      pwd_value="${pwd_value%$'\r'}"

      if [ -z "$pwd_value" ]; then
        # Password value is empty - FAIL FAST (file exists but password is empty)
        echo "ERROR: Password value for key '${pwd_key}' is empty in '${pwd_file}'. File exists but is malformed. Expected format: ${pwd_key}=<password>" >&2
        exit 1
      fi

      # Successfully resolved password from file
      config="${config//${token}/${pwd_value}}"
      echo "===> Resolved keystorePassword from ${pwd_file}" >&2
    fi
  fi

  echo "$config"
}
