#!/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 [<options>] <file> <option>"
  echo "Example: ngcpcfg del /etc/ngcp-config/config.yml unnecessary.option"
  echo "Options:"
  echo "  --diff: show difference(s) for the applied changes"
}

## }}}

RC=0
b_show_diff=false

if [ "${#:-}" == "2" ]; then
  file="$1"
  option="$2"
elif [ "${#:-}" == "3" ]; then
  if [ "$1" == "--diff" ]; then
    b_show_diff=true
  else
    log_error "unsupported option '$1'. Exiting."
    help >&2
    exit 1
  fi
  file="$2"
  option="$3"
else
  help >&2
  exit 1
fi

[ -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=$?


if [ "${RC}" = "0" ] && "${b_show_diff:-false}"; then
  log_debug "${SCRIPTS}/diff || true"
  "${SCRIPTS}"/diff || true
fi

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

exit ${RC:-0}

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