#!/bin/sh
set -e

# Automatically update postfix alias databases (.db) if their plaintext sources
# are part of the incoming commit; also automatically reload postfix if needed.

# Only implemented with git backend
if [ "$VCS" != "git" ]; then
	echo "$VCS not supported" >&2
	exit 2
fi

# If a binary database is modified, then postfix must be reloaded.
reload_postfix="false"

# Just query modified files in /etc
query_files_to_commit() {
	git diff --name-only
	git diff --name-only --cached
}
TO_BE_COMMITED="$(query_files_to_commit)"

# Just query databases that postfix is aware of (avoid to hardcode them here,
# or to source another cofiguration file, etc.)
query_postfix_databases() {
	local db POSTCONF="$(postconf -p)"
	for db in $(postconf -m); do
		echo "${POSTCONF}" |
		grep -o "\<${db}:/etc/[^[:space:],]\+" || true
	done | sort -u
}

for DB in $(query_postfix_databases); do
	if echo "${TO_BE_COMMITED}" | grep -q "^${DB#*:/etc/}$"; then
		reload_postfix="true"
		case "${DB}" in
			hash:*aliases)
				postalias ${DB} ;;
			*)	postmap ${DB#*:} ;;
		esac
	fi
done

if [ "${reload_postfix}" = "true" ]; then
	# Say:
	echo "Some postfix databases have changed, please reload postfix" >&2
	# Or do:
	#postfix reload
else
	true
fi

