#!/usr/bin/env bash
set -eu

# etckeeper hook for portage's conf-update hooks (e.g. invoked by
# dispatch-conf). Requires portage > 3.0.22.

# Do nothing if etckeeper is not initialized.
if [[ ! -f "/etc/etckeeper/etckeeper.conf" ]]; then
	exit
fi

echo "conf-update.d ${@}"

case "${1}" in
	pre-session)
		echo "Commiting uncommited changes before starting a configuration update session"
		etckeeper pre-install
		;;
	post-session)
		echo "Commiting uncommited changes before after finishing a configuration update session"
		etckeeper post-install
		;;
	post-update)
		ACTION=${1}
		FILE_PATH=${2}
		FILE=$(basename "${FILE_PATH}")

		echo "Commiting changes for ${FILE}"
		etckeeper vcs add "${FILE_PATH}"
		etckeeper vcs commit -m "${FILE}: ${ACTION} (conf-update.d hook)"
	;;
esac