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

# shellcheck source=./functions/main
. "${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

while [ -n "${1:-}" ]; do
  case "$1" in
    --diff)
      b_show_diff=true
      shift
      ;;
    --*)
      log_error "unsupported option '$1'. Exiting."
      help >&2
      exit 1
      ;;
    *)
      break
      ;;
  esac
done

if [ "${#:-}" != "2" ]; then
  help >&2
  exit 1
fi

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}'"

log_debug "${HELPER}/del-value '${file}' '${option}' || RC=\$?"
"${HELPER}/del-value" "${file}" "${option}" || RC=$?

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

exit ${RC:-0}

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