#!/bin/bash
# Purpose: decrypt ngcp configuration archive
################################################################################

set -e
set -u
set -o pipefail

# support for testsuite, assume defaults if unset
FUNCTIONS="${FUNCTIONS:-/usr/share/ngcp-ngcpcfg/functions/}"
HELPER="${HELPER:-/usr/share/ngcp-ngcpcfg/helper/}"

if ! [ -r "${FUNCTIONS}"/logs ] ; then
  printf "Error: %s/logs 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

# We cannot source ${FUNCTIONS}/main as we are missing a bunch of
# configuration files that are supposed to be available, therefore we
# source the ${FUNCTIONS}/logs file instead.

timestamp_replacementchars='' # unset by default
# shellcheck disable=SC1090
. "${FUNCTIONS}"/logs
. "${FUNCTIONS}"/openpgp

setup_shared_config() {
  if ! [ -d /mnt/glusterfs/mgmt-share ] ; then
    log_warn "Looks like glusterfs is not running, can not install it automatically.

Please execute the following command on one node
as soon as glusterfs share is mounted again:

  git clone --bare /etc/ngcp-config /mnt/glusterfs/ngcpcfg-share
  ${HELPER}/restore-permissions /mnt/glusterfs/ngcpcfg-share

"
    return 0
  fi

  if [ -d /mnt/glusterfs/ngcpcfg-share ] ; then
    log_info "Shared storage exists already, ignoring request to (re)install it."
  else
    log_info "Copying git repository to shared storage."
    git clone --bare /etc/ngcp-config /mnt/glusterfs/ngcpcfg-share | sed "s/^/${timestamp_replacementchars}/"
    "${HELPER}"/restore-permissions /mnt/glusterfs/ngcpcfg-share
  fi
}

# main script
openpgp_setup

RC=0
TARGZPGP=
# XXX: Try the "-crypted.gpg" terminator for backwards compatibility.
for file in /etc/ngcp-config.tgz.pgp /etc/ngcp-config-crypted.tgz.gpg; do
  if [ -r "${file}" ]; then
    TARGZPGP="${file}"
    break
  fi
done

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

openpgp_prompt_password

# For backwards compatibility we switch to the root directory, for old
# encrypted tarballs that stripped the leading /.
cd /
if ! openpgp_decrypt <"${TARGZPGP}" | tar zxPf - ; then
  log_error "Error while decrypting or restoring ${TARGZPGP}"
  RC=1
else
  log_info "Successfully restored configuration archive ${TARGZPGP}"
  log_info "Now you should be able to run 'ngcpcfg apply' again."
fi

openpgp_reset_password

# only for PRO/CARRIER
if [ -r "${FUNCTIONS}"/ha_features ] ; then
  setup_shared_config
else
  log_info "Ignoring shared configuration (PRO/CARRIER only)."
fi

exit "${RC}"

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