#!/bin/bash
# Purpose: set config value
################################################################################

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 disable=SC1090
. "${FUNCTIONS}"/main

## functions {{{
help() {
  echo "Usage: ngcpcfg set [<options>] <file> <key>"
  echo "Example: ngcpcfg set /etc/ngcp-config/maintenance.yml general.maintenance=yes"
  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 [[ ${#:-} -lt 2 ]]; then
  help >&2
  exit 1
fi

file="$1"
shift
declare -a data=("$@")

[ -f "${file}" ] || (log_error "missing ${file}. Exiting." ; exit 1)
[ -z "${data[*]}" ] && (log_error "missing data to set. Exiting." ; exit 1)

# Check whether we should use different permissions when creating the file.
CREATEFILE=no
if [ ! -f "${file}" ]; then
  CREATEFILE=yes
  if [ "${file}" = "${NETWORK_CONFIG:-}" ]; then
    MODE="${NETWORK_CONFIG_CHMOD}"
    USER="${NETWORK_CONFIG_USER}"
    GROUP="${NETWORK_CONFIG_GROUP}"
  else
    MODE="${CONFIG_CHMOD}"
    USER="${CONFIG_USER}"
    GROUP="${CONFIG_GROUP}"
  fi
fi

log_debug "Received data: ${data[*]}"
log_debug "${HELPER}/set-value '${file}' ${data[*]} || RC=\$?"
"${HELPER}/set-value" "${file}" "${data[@]}" || RC=$?

if [ "${CREATEFILE}" = "yes" ]; then
  chmod "${MODE}" "${file}"
  chown "${USER}" "${file}"
  chgrp "${GROUP}" "${file}"
fi

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

exit ${RC}

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