#!/bin/bash
# Purpose: delete config option from YAML file
################################################################################

set -e
set -u

# support testsuite
FUNCTIONS="${FUNCTIONS:-/usr/share/ngcp-ngcpcfg/functions/}"
HELPER="${HELPER:-/usr/share/ngcp-ngcpcfg/helper/}"
SCRIPTS="${SCRIPTS:-/usr/share/ngcp-ngcpcfg/scripts/}"

if ! [ -r "${FUNCTIONS}"/main ] ; then
  printf "Error: %s/main could not be read. Exiting.\n" "${FUNCTIONS}">&2
  exit 1
fi

. "${FUNCTIONS}"/main

## functions {{{
help() {
  echo "Usage: ngcpcfg del <file> <option>"
  echo "Example: ngcpcfg del /etc/ngcp-config/config.yml unnecessary.option"
}

## }}}

[ "${#:-}" -ne 2 ] && (help >&2 ; exit 1)

file="$1"
option="$2"

[ -f "${file}" ] || (log_error "missing ${file}. Exiting." ; exit 1)
[ -z "${option}" ] && ( log_error "missing option to set. Exiting." ; exit 1)
log_debug "Deleting option '${option}' from '${file}'"

perl_line="delete \$yaml->{${option//./\}->\{}};"
log_debug "perl line: ${perl_line}"

tmp=$(mktemp)
log_debug "Temporary perl file: ${tmp}"

cat > "${tmp}" << EOF
use strict;
use warnings;
use YAML::XS;
my \$file="${file}";
my \$yaml = YAML::XS::LoadFile("\$file");

${perl_line}

YAML::XS::DumpFile(\$file, \$yaml);
EOF

log_debug "perl -wCSD \"${tmp}\" || RC=$?"
perl -wCSD "${tmp}" || RC=$?

log_debug "ngcpcfg diff | tail -n +5 || true"
ngcpcfg diff | tail -n +5 || true

if [ -n "${DEBUG:-}" ] ; then
  log_debug "Not removing temporary file ${tmp}"
else
  rm -f "${tmp}"
fi

exit ${RC:-0}

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