#!/usr/bin/env sh
# (Copyright) [2014 - 2025] Confluent, Inc.

#
# Use shellcheck to lint this file
#

set -ue

# Check if a specific flag is present in the arguments
has_flag() {
  flag_to_check="$1"
  shift
  for arg in "$@"; do
    if [ "$arg" = "$flag_to_check" ]; then
      return 0  # true
    fi
  done
  return 1  # false
}

# Default configs
config_dir="/etc/confluent/usm-agent"
bin_dir="/usr/bin"
envoy_dir="/usr/libexec/confluent/usm-agent"

# Use USM_AGENT_CONFIG_DIR if set, else use /etc/confluent/usm-agent
if [ -n "${USM_AGENT_CONFIG_DIR:-}" ]; then
  config_dir="${USM_AGENT_CONFIG_DIR}"
fi

# Use USM_AGENT_BIN_DIR if set, else use /usr/bin
if [ -n "${USM_AGENT_BIN_DIR:-}" ]; then
  bin_dir="${USM_AGENT_BIN_DIR}"
fi

# Use USM_AGENT_ENVOY_DIR if set, else use /usr/libexec/confluent/usm-agent
if [ -n "${USM_AGENT_ENVOY_DIR:-}" ]; then
  envoy_dir="${USM_AGENT_ENVOY_DIR}"
fi

# Replace all args with USM_AGENT_CUSTOM_ARGS environment variable
if [ -n "${USM_AGENT_CUSTOM_ARGS:-}" ]; then
    set -- $envoy_dir/envoy ${USM_AGENT_CUSTOM_ARGS}
else
    set -- $envoy_dir/envoy "$@"
fi

# Check if the -c flag is present in the arguments
if has_flag "-c" "$@"; then
  # Start envoy with the passed configuration and any additional arguments passed to this script
  exec "${@}"
else
  # Generate envoy configs from USM Agent properties
  $bin_dir/usm-agent-configgen "$config_dir"
  # Start envoy with the generated configuration and any additional arguments passed to this script
  exec "${@}" -c "$config_dir/usm-agent.yaml"
fi
