#!/bin/bash

set -euo pipefail

rsync -aAXH /etc/ngcp-config \
  --exclude client-auth-ca.crt \
  --exclude ngcpcfg.cfg \
  --exclude ngcpcfg.d/shared_storage.cfg \
  --exclude templates \
  /ngcp-fallback/etc/

cp -a /etc/default/ngcp-roles /ngcp-fallback/etc/default/
cp -at /ngcp-fallback/etc/    /etc/{ngcp_nodename,resolv.conf,sipwise_ngcp_version,ngcp_hostname}

openvpn_certs_path=$(ngcpcfg get openvpn.keys_filename_template)
openvpn_certs_path="${openvpn_certs_path%/*}"
# Target directory is a parent dir of openvpn_certs_path in /ngcp-fallback partition
target_openvpn_certs_path="/ngcp-fallback/${openvpn_certs_path%/*}"

# Check if certs are located in known shared directories
if [[ "${openvpn_certs_path}" =~ ^/etc/ngcp-config ]]; then
  exit 0
elif [[ "${openvpn_certs_path}" =~ ^/ngcp-data ]]; then
  exit 0
fi
if [[ -d "${openvpn_certs_path}" ]]; then
  echo "Copying content of ${openvpn_certs_path} dir to ${target_openvpn_certs_path}"
  cp -a "${openvpn_certs_path}" "${target_openvpn_certs_path}"
fi
