#!/usr/bin/env bash
#
# Copyright 2020 Confluent Inc.
#
# Shared JMX setup function for all Confluent Platform components
# This handles copying JMX password and access control files from Kubernetes secret mounts
# to the component's config directory
#
# The JVM requires the password file to be a regular file (not a symlink), so we must copy
# the files from the Kubernetes secret mount. Kubernetes mounts secrets as symlinks by default.
#
# File permissions are already set by the operator via volume DefaultMode:
# - JMX password: 0600 (read/write for owner only)
# - JMX access control: 0644 (read for all, write for owner)

setup_jmx_files() {
  local component_name=$1
  local dest_dir=$2

  local JMX_PASSWORD_SOURCE="/mnt/secrets/jmx-password-${component_name}/jmxremote.password"
  local JMX_PASSWORD_DEST="${dest_dir}/jmxremote.password"
  local JMX_ACCESS_SOURCE="/mnt/secrets/jmx-access-${component_name}/jmxremote.access"
  local JMX_ACCESS_DEST="${dest_dir}/jmxremote.access"

  if [ -f "${JMX_PASSWORD_SOURCE}" ]; then
    echo "===> Copying JMX password file"
    cp "${JMX_PASSWORD_SOURCE}" "${JMX_PASSWORD_DEST}"
    chmod 600 "${JMX_PASSWORD_DEST}"
    echo "===> JMX password file permissions: $(ls -l ${JMX_PASSWORD_DEST})"
  fi

  if [ -f "${JMX_ACCESS_SOURCE}" ]; then
    echo "===> Copying JMX access control file"
    cp "${JMX_ACCESS_SOURCE}" "${JMX_ACCESS_DEST}"
    chmod 644 "${JMX_ACCESS_DEST}"
    echo "===> JMX access file permissions: $(ls -l ${JMX_ACCESS_DEST})"
  fi
}