#!/bin/bash
# Purpose: perform post-build actions
################################################################################

set -e
set -u
set -o pipefail

# 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

timestamp_replacementchars=''
# shellcheck source=./functions/main
. "${FUNCTIONS}"/main

# main script

cd "$NGCPCTL_MAIN"

if [ -z "${NO_DB_SYNC:-}" ]; then
  declare -a configs
  configs+=("$NGCPCTL_CONFIG")
  configs+=("$CONSTANTS_CONFIG")
  if [ -f "${RTP_INTERFACES_CONFIG}" ]; then
    configs+=("$RTP_INTERFACES_CONFIG")
  fi
  configs+=("$NETWORK_CONFIG")
  configs+=("$SITES_CONFIG")

  log_info "Synchronizing MariaDB database: "
  "${HELPER}/sync-db" "${configs[@]}" 2>&1 \
    | sed "s/^/$timestamp_replacementchars/" 2>&1 \
    | tee >(logger -t ngcpcfg --id="${NGCPCFG_PID}") || true
else
  log_debug "no-db-sync: skipping 'sync-db'"
fi

if [ -z "${NO_DB_SYNC:-}" ]; then
  log_info "Synchronizing MariaDB grants/credentials"
  ngcp-sync-db-grants \
    | sed "s/^/$timestamp_replacementchars/"
  ngcp-sync-db-creds \
    | sed "s/^/$timestamp_replacementchars/"
  if [ -z "${NGCP_TYPE:-}" ]; then # SPCE
    # shellcheck disable=SC1091
    . /etc/default/ngcp-roles
  fi
  if [ "${NGCP_TYPE}" == "carrier" ] && [ "${NGCP_IS_PROXY}" == "yes" ]; then
    # shellcheck disable=SC1091
    . /etc/default/ngcp-db

    log_info "Synchronizing MariaDB grants/credentials for ${LOCAL_DBHOST}:${LOCAL_DBPORT}"
    ngcp-sync-db-grants \
      --db-host "${LOCAL_DBHOST}" \
      --db-port "${LOCAL_DBPORT}" \
      --no-warnings \
      | sed "s/^/$timestamp_replacementchars/"
    ngcp-sync-db-creds \
      --db-host "${LOCAL_DBHOST}" \
      --db-port "${LOCAL_DBPORT}" \
      --no-warnings \
      | sed "s/^/$timestamp_replacementchars/"
  fi
else
  log_debug "no-db-sync: skipping 'ngcp-sync-db-grants' + 'ngcp-sync-db-creds'"
fi

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