#!/bin/bash
# This has to be executed inside a NGCP docker image
# on the cfg-schema repository
#
# docker -D pull docker.mgm.sipwise.com/sipwise/ce-trunk:latest
# docker run --rm \
#  -v /tmp/schema:/schema:rw \
#  -v $(pwd):/source:ro \
#  docker.mgm.sipwise.com/sipwise/ce-trunk:latest \
#  bash -c "export LC_ALL=en_US.utf8 && cd /schema && \
#    CFG_BASE=/source/cfg_scripts/ /source/build_utils/ngcp-build-cfg-files"
set -euEo pipefail

SCRIPTS_DIR="${CFG_BASE:-/usr/share/ngcp-cfg-schema/cfg_scripts}"
SCHEMA_DIR="${SCHEMA_DIR:-/source/schema}"
DYN_KEYS=()
DYN_KEYS+=('bootenv.netscript.swapfilesize')
DYN_KEYS+=('kamailio.proxy.shm_mem')
declare -A DYN_VALUES

get_dynamic_values () {
  local file="$1"
  for key in "${DYN_KEYS[@]}"; do
    DYN_VALUES[$key]=$(yq ".${key}" "${file}")
    echo "$key = ${DYN_VALUES[$key]}"
  done
}

restore_dynamic_values () {
  local file="$1"
  for key in "${DYN_KEYS[@]}"; do
    ngcpcfg set "${file}" "${key}=${DYN_VALUES[$key]}"
  done
}

for type in ce pro carrier; do
  if [[ "${type}" == 'ce' ]]; then
    schema_type="${type}"
    ngcp_type='spce'
    nodename='spce'
  elif [[ "${type}" == 'pro' ]]; then
    schema_type="${type}"
    ngcp_type='sppro'
    nodename='sp1'
  elif [[ "${type}" == 'carrier' ]]; then
    schema_type='pro'
    ngcp_type='carrier'
    nodename='web01a'
  fi

  get_dynamic_values "${SCHEMA_DIR}/${schema_type}/config.yml"

  cfg_dir="${type}"
  mkdir -p "${cfg_dir}"

  echo "Executing ngcp-update-cfg-schema"
  NGCP_HOSTNAME="${nodename}" ngcp-update-cfg-schema -d "${cfg_dir}" \
    -t "${nodename}" -u "${SCRIPTS_DIR}" -n "${ngcp_type}"

  echo "Dumping ${cfg_dir}/cfg_schema.db into ${cfg_dir}/cfg_schema.sql"
  echo -e ".mode insert cfg_schema\n.out ${cfg_dir}/cfg_schema.sql
    SELECT id, revision, \"${nodename}\" FROM cfg_schema ORDER BY id ASC" \
    | sqlite3 "${cfg_dir}/cfg_schema.db"
  # It's necessary to specify columns so it takes default NOW() for applied_at
  sed -ri 's/(INSERT INTO cfg_schema)/\1 (id, revision, node)/g' \
    "${cfg_dir}/cfg_schema.sql"

  echo "Dropping ${cfg_dir}/cfg_schema.db"
  rm -f "${cfg_dir}/cfg_schema.db"

  restore_dynamic_values "${cfg_dir}/config.yml"
done

# We have different network.yml for Pro and Carrier so have to use
# workaround here
cp carrier/network.yml pro/network_carrier.yml
rm -rf carrier
