#!/usr/bin/env bash
#
# Resolves ${file:path:key} references in JVM options strings.
# This is needed because JVM system properties cannot natively resolve Kafka's
# FileConfigProvider syntax.
#
# Usage:
#   source /mnt/config/resolve-jvm-opts.sh
#   resolved="$(resolve_jvm_file_refs "$jvm_opts_string")"
#

resolve_jvm_file_refs() {
  local opts="$1"
  local default_password="mystorepassword"

  # Resolve all ${file:...} references in JVM options
  while [[ "$opts" =~ \$\{file:([^:]+):([^}]+)\} ]]; do
    local file_path="${BASH_REMATCH[1]}"
    local key_name="${BASH_REMATCH[2]}"
    local token="\${file:${file_path}:${key_name}}"

    if [ ! -e "$file_path" ]; then
      # File doesn't exist - fall back to default password
      # This can happen when directoryPathInContainer is set but password file is not injected
      opts="${opts//${token}/${default_password}}"
      echo "WARN: JVM option references file '${file_path}' which does not exist, using default password" >&2
    else
      # File exists - it MUST be valid (fail-fast if malformed)
      local value
      value="$(grep "^${key_name}=" "$file_path" 2>/dev/null | head -1 | cut -d'=' -f2-)"
      value="${value%$'\n'}"
      value="${value%$'\r'}"

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

      # Successfully resolved value from file
      opts="${opts//${token}/${value}}"
      echo "===> Resolved ${key_name} from ${file_path} for JVM opts" >&2
    fi
  done

  echo "$opts"
}
