#!/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

. "${FUNCTIONS}"/main

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"${HA_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
if ! type -p gpg &>/dev/null ; then
  log_error "gpg binary not found, exiting."
  exit 1
fi

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

RC=0
TARGZ=/etc/ngcp-config-crypted.tgz
FILES=$(get_config_file_list)
# shellcheck disable=SC2086
tar zcf "$TARGZ" /etc/ngcp-config/ $FILES /etc/.git
if gpg --symmetric "$TARGZ" ; then
  log_info "Successfully created crypted ngcpcfg configuration archive ${TARGZ}.gpg"
  # ensure we don't leave the unencrypted version behind
  rm -f "${TARGZ}"
else
  log_error "Error while setting up ${TARGZ}.gpg"
  # ensure we don't leave the unencrypted version behind
  rm -f "${TARGZ}"
  exit 1
fi

log_info_n "Now really erase all configuration files managed by ngcpcfg? [y/N] "
a='' ; read a
if [[ "$a" == "y" ]] || [[ "$a" == "Y" ]] ; then
  rm -rf "$NGCPCTL_MAIN" ; rm -f "$TARGZ"
  # shellcheck disable=SC2086
  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 "$RC"

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