#!/bin/bash
# Purpose: wrapper around etckeeper for usage inside ngcpcfg
################################################################################

set -e
set -u
set -o pipefail

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

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

timestamp_replacementchars=''
# shellcheck disable=SC1090
. "${FUNCTIONS}"/main

# main script

log_debug "cd ${NGCPCTL_BASE}"
cd "${NGCPCTL_BASE}"

log_debug "type -p etckeeper"
if ! type -p etckeeper &>/dev/null ; then
  log_warn "etckeeper is not available, skipping etckeeper execution"
  exit 0
fi

log_debug "test -d .git"
if ! [ -d .git ] ; then
  log_warn "etckeeper has not been initialized yet, skipping etckeeper execution"
  exit 0
fi

# commit message
if [ -z "${1:-}" ] ; then
  msg="committing uncommented changes"
else
  msg="$*"
fi

log_info "Checking state of ${NGCPCTL_BASE} files"
if is_git_clean ; then
  log_info "OK:   nothing to commit."
else
  log_debug "etckeeper commit '$msg via \"ngcpcfg apply\"'"
  etckeeper commit "$msg via \"ngcpcfg apply\"" | sed "s/^/$timestamp_replacementchars/"
fi

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