#!/bin/bash
# Purpose: get a value based on ngcpcfg's config
################################################################################

set -e
set -u

get_value() {
  local value="$1"
  local rc=0
  # assume safe defaults
  umask 0077

  input_file="$(mktemp -t ngcpcfg-get-in.XXXXXXXXXX)"
  echo "[% $value %]" > "${input_file}"
  output_file="$(mktemp -t ngcpcfg-get-out.XXXXXXXXXX)"

  if "${HELPER}/tt2-process" -p -q "${ARGS[@]}" "${input_file}" "${output_file}" >/dev/null 2>&1 ; then
    cat "${output_file}"
  else
    log_error "cannot process request for '${value}'!"
    rc=1
  fi
  rm -f "${input_file}" "${output_file}"

  return "${rc}"
}

if [ "${#:-}" -ne 1 ] ; then
  echo "Usage: ngcpcfg get <key>" >&2
  echo "Example: ngcpcfg get ntp.servers" >&2
  exit 1
fi

# support testsuite
FUNCTIONS="${FUNCTIONS:-/usr/share/ngcp-ngcpcfg/functions/}"
HELPER="${HELPER:-/usr/share/ngcp-ngcpcfg/helper/}"

if ! [ -r "${FUNCTIONS}"/main ] ; then
  printf "Error: %s/main could not be read. Exiting.\n" "${FUNCTIONS}">&2
  exit 1
fi

# shellcheck disable=SC1090
. "${FUNCTIONS}"/main

# Get the list of configs in proper order to load.
declare -a ARGS
for f in ${NGCPCTL_CONFIG:-} ${NODE_CONFIG:-} ${PAIR_CONFIG:-} ${HOST_CONFIG:-} ${LOCAL_CONFIG:-} ${MAINTENANCE_CONFIG:-} ${NETWORK_CONFIG:-} "${EXTRA_CONFIG_FILES[@]}" ${CONSTANTS_CONFIG:-} ; do
  ARGS+=("-c" "${f}")
done

# main script

# TODO: detect HASH and try to create template to get those values?
res="$(get_value "$1")"
if [[ $res =~ ^ARRAY\(0x.+\)$ ]]; then
  get_value "$1.join(' ')"
else
  echo "$res"
fi

exit 0

## END OF FILE #################################################################