#!/usr/bin/env bash

#
# Generate all the configuration files
# Get all the values from the VLS_DIR
# Process each template from the TPL_DIR with this values
#

ENV_FILE=${ENV_FILE:-/var/run/one-context/one_env}
TPL_DIR="/usr/share/builder/templates"
VLS_DIR="/usr/share/builder/values"
CONFIG=""

. ${ENV_FILE}

BTR="$(command -v btr)"
if [ "${?}" -ne 0 ]; then
  echo "Warning: Nothing to do the templater is not installed"
  exit 0
fi

if [ ! -e "${TPL_DIR}" ]; then
  echo "Error: The template dir is missing (${TPL_DIR})"
  exit 1
fi

if [ ! -e "${VLS_DIR}" ]; then
  echo "Error: The template dir is missing (${VLS_DIR})"
  exit 1
fi

jsonQuery() {
  local data="${1}"
  local query="${2}"
  echo "${data}" | jq -cr "${query}"
}

# NAME: @jsonMerge
# AIM: Merge two json structures
# NOTES:
#   The last one has de last word
#   if you have the same key in A and B
#   this keeps the value of the B structure.
# PARAMS:
#  $1: original JSON Structure
#  $2: updated JSON Structure
jsonMerge() {
  local data="${1}"
  local data2="${2}"

  echo "${data} ${data2}" | jq -cr -s ".[0] * .[1]"
}

getValues() {

  local values=""

  for file in $(find ${VLS_DIR} -name "*.json"); do
    values="${values}$(cat ${file})"
  done

  if [ -n "${RAW_CONFIG}" ]; then
    values="$(jsonMerge ${values} ${RAW_CONFIG})"
  fi

  for key in $(echo ${values} | jq -cr '.|keys[]'); do
    ukey=${key^^}
    if [ -n "${!ukey}" ]; then
      values="$(jsonMerge "${values}" "{\"${key}\":\"${!ukey}\"}")"
    fi
  done
  echo ${values}
}

processTemplates() {
  ${BTR} -t ${TPL_DIR} -c "${1}"
}
VALUES=$(getValues)
echo ${VALUES}
processTemplates "${VALUES}"