#!/bin/sh
#
# /etc/cron.hourly/etckeeper-warn-changes
#
#  * Envoie un mail une fois par jour si des modifications dans /etc n'ont
#    pas été enregistrés,
#  * Si toutes les modifications ont été enregistrées, et que le dernier
#    enregistrement a plus d'une heure, on envoie les modifications dans
#    le dépôt $BACKUP_REPOSITORY.
#
# Le dépôt $BACKUP_REPOSITORY est configuré automatiquement s'il n'existe pas.
# Les modifications reçus par ce dépôt seront envoyé à l'adresse $MAILTO par le
# script `/usr/share/doc/git-core/contrib/hooks/post-receive-email`.
#
# Le date de dernière modification du fichier $LAST_WARNING est utilisée pour
# enregistrer la date du dernier rappel envoyé.
#

set -e

test -d /etc/.git || exit 0

LAST_WARNING="/var/lib/etckeeper-last-warning"
BACKUP_REPOSITORY="/var/backups/etc.git"
MAILTO="root@localhost"
SUBJECT_PREFIX="[$(hostname -f)]"

export LC_CTYPE="fr_FR.UTF-8"

alias etc_git="git --git-dir='/etc/.git' --work-tree='/etc'"

unclean_message() {
	cat <<-EOF
	Les fichiers suivant n'ont pas été enregistrés avec etckeeper :

	$(etc_git ls-files --modified --deleted --others --exclude-standard)

	Les dernières connections sont :

	$(last -5)
	EOF
}

init_backup_repository() {
	mkdir -p "$BACKUP_REPOSITORY"
	chmod 700 "$BACKUP_REPOSITORY"
	git --git-dir="$BACKUP_REPOSITORY" init --bare >/dev/null

	dpkg-statoverride --update --add root root 755 \
		/usr/share/doc/git-core/contrib/hooks/post-receive-email
	ln -nsf /usr/share/doc/git-core/contrib/hooks/post-receive-email \
		"$BACKUP_REPOSITORY/hooks/post-receive"
	git --git-dir="$BACKUP_REPOSITORY" config hooks.mailinglist "$MAILTO"
	git --git-dir="$BACKUP_REPOSITORY" config hooks.emailprefix "$SUBJECT_PREFIX "
	echo "/etc" >"$BACKUP_REPOSITORY/description"
}

has_backup_remote() {
	etc_git show-ref --quiet --verify -- "refs/remotes/backup/master"
}

setup_backup_remote() {
	etc_git remote add -m master backup "$BACKUP_REPOSITORY"
}

if etckeeper unclean; then
	if ! [ -f "$LAST_WARNING" ]; then
		unclean_message | mail -s "$SUBJECT_PREFIX Des changements de configuration n'ont pas été enregistrés" "$MAILTO"
		touch "$LAST_WARNING"
	elif  [ "$(find "$LAST_WARNING" -mtime 1)" ]; then
		unclean_message | mail -s "$SUBJECT_PREFIX Des changements de configuration n'ont toujours pas été enregistrés..." "$MAILTO"
		touch "$LAST_WARNING"
	fi
elif [ -z "$(etc_git rev-list $(etc_git rev-parse --since='one hour') master)" ]; then
	test -d "$BACKUP_REPOSITORY" || init_backup_repository
	has_backup_remote || setup_backup_remote

	etc_git push backup master 2>/dev/null
	rm -f "$LAST_WARNING"
fi
