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

set -e
set -u

get_value() {
  # assume safe defaults
  umask 0077

  input_file="$(mktemp)"
  echo "[% $1 %]" > "${input_file}"
  output_file="$(mktemp)"

  if "$TT_WRAPPER" "${input_file}" > "${output_file}" 2>/dev/null ; then
    cat "${output_file}"
  else
    RC=1
  fi
  rm -f "${input_file}" "${output_file}"
}

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

. "${FUNCTIONS}"/main

TT_WRAPPER="${HELPER}/tt2-wrapper"

# Kill all previous started tt2-daemon Perl processes if they were not stopped properly
killall tt2-daemon 2>/dev/null || true

if [ -n "${NGCP_SOCKETFILE:-}" ] ; then
  log_debug "Using $NGCP_SOCKETFILE as tt2-daemon socket file as set via 'NGCP_SOCKETFILE'."
else
  NGCP_SOCKETFILE='/var/run/ngcpcfg.socket'
fi
rm -f "${NGCP_SOCKETFILE}"

# Start new tt2-daemon Perl process
"${HELPER}"/tt2-daemon --quiet

# Load all the configs in proper order and check their avialability and valid YAML syntax
for f in ${NGCPCTL_CONFIG:-} ${HOST_CONFIG:-} ${LOCAL_CONFIG:-} ${NETWORK_CONFIG:-} "${EXTRA_CONFIG_FILES[@]}" ${CONSTANTS_CONFIG:-} ; do
  if [ -r "$f" ] ; then
    if ! "${HELPER}/tt2-wrapper" "/dev/null" "${f}" ; then
      log_error "tt2-daemon cannot load ${f}:"
      "${HELPER}/tt2-wrapper" "/dev/null" "${f}"
      exit 1
    fi
  fi
done

# main script
RC=0

# 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

# Kill all previous started tt2-daemon Perl processes
killall tt2-daemon 2>/dev/null || true
rm -f "${NGCP_SOCKETFILE}"

exit "$RC"

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