#!/bin/bash
# Purpose: encrypt ngcp configuration files
################################################################################

set -e
set -u

# 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
if ! [ -r "${FUNCTIONS}"/openpgp ] ; then
  printf "Error: %s/openpgp could not be read. Exiting.\n" "${FUNCTIONS}" >&2
  exit 1
fi

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

get_config_file_list() {
  for dir in ${CONFIG_POOL} ; do
    # shellcheck disable=SC2044
    for file in $(find "${TEMPLATE_POOL_BASE}/${dir}" -name \*.tt2 -o -name \*.tt2"${NODE_FILE:-}") ; do
      x=${file##"${NGCPCTL_MAIN}"/templates/} # drop leading /etc/ngcp-config
      y=${x%%.tt2}                            # drop trailing suffix '.tt2'
      y=${y%%.tt2.sp1}                        # drop trailing suffix '.tt2.sp1'
      y=${y%%.tt2.sp2}                        # drop trailing suffix '.tt2.sp2'
      y=${y%%.customtt}                       # drop trailing suffix '.customtt'
      y=${y%%.patchtt}                        # drop trailing suffix '.patchtt'
      # if the file does not exist (e.g. because "ngcpcfg apply"
      # hasn't been executed yet for whatever reason, then don't
      # report missing files, otherwise tar will complain
      if [ -r "${y}" ] ; then
        echo "${y}"
      fi
    done
  done
}

# main script
openpgp_setup

# ensure created files can be read by root only
umask 066

mapfile -t FILES < <(get_config_file_list)
if [ "${#FILES[@]}" = "0" ] ; then
  log_error "No ngcpcfg config files to back up. Aborting."
  exit 1
else
  log_debug "Packing configs: ${FILES[*]}"
fi

TARGZ=/etc/ngcp-config.tgz
TARGZPGP="${TARGZ}.pgp"

openpgp_prompt_password

if tar zcPf - /etc/ngcp-config/ "${FILES[@]}" /etc/.git \
     | openpgp_encrypt >"${TARGZPGP}" ; then
  log_info "Successfully created encrypted ngcpcfg configuration archive ${TARGZPGP}"
else
  log_error "Error while setting up ${TARGZPGP}"
  exit 1
fi

openpgp_reset_password

log_info_n "Now really erase all configuration files managed by ngcpcfg? [y/N] "
a='' ; read -r a
if [[ "$a" == "y" ]] || [[ "$a" == "Y" ]] ; then
  rm -rf "${NGCPCTL_MAIN}"
  rm -f "${FILES[@]}" ; rm -rf /etc/.git
  # make sure we don't leavy any stuff on shared storage
  rm -rf /ngcp-data/glusterfs/export/ngcpcfg-share
  rm -rf /mnt/glusterfs/ngcpcfg-share/
else
  log_info "Skipping as requested."
fi

exit 0

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