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

# main script

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

if ! [ "${NGCP_TESTSUITE:-false}" = "true" ]; then
  log_debug "type -p etckeeper"
  if ! type -p etckeeper &>/dev/null ; then
    log_warn "etckeeper is not available, skipping etckeeper execution"
    exit 0
  fi
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
  if ! [ "${NGCP_TESTSUITE:-false}" = "true" ]; then
    log_debug "etckeeper commit '$msg via \"ngcpcfg apply\"'"
    etckeeper commit "$msg via \"ngcpcfg apply\"" | sed "s/^/$timestamp_replacementchars/"
  else
    # Do a manual git commit to simulate etckeeper
    log_debug "git add . ; git commit -m '$msg via \"ngcpcfg apply\"'"
    git add .
    git commit -m "$msg via \"ngcpcfg apply\""
  fi
fi

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