#!/bin/sh

# Verify that exim4-daemon-mod does not use SPF (libspf) at runtime
# as it is intended on Ubuntu.
# Verify also that removing SPF support from exim4-daemon-mod does not impact
# exim4: SPF must be genuinely absent, and the daemon must still work.

set -e

runandshow() {
	count=0
	printf '===============\n%s: running ' "$0"
	for i in "$@" ; do
		printf "argv[%i]=[%s] " "$count" "$i"
		count=$(($count+1))
	done
	echo
	"$@"
}

exim=/usr/sbin/exim4

# --- 0. The exim4 binary under test must be provided by exim4-daemon-mod. ----
# The SPF checks below are only meaningful for that daemon variant, so verify
# that /usr/sbin/exim4 is actually owned by the exim4-daemon-mod package.
owner="$(dpkg -S "$exim" 2>/dev/null | cut -d: -f1)"
if [ "$owner" != "exim4-daemon-mod" ]; then
	echo "FAIL: $exim is provided by '${owner:-no package}', not exim4-daemon-mod"
	exit 1
fi

# --- 1. The daemon itself must still start up and report its version. -------
runandshow $exim -bV

# --- 2. SPF must no longer be advertised as a (dynamic) lookup/feature. ------
# When built as a module (SUPPORT_SPF=2) exim lists "spf" under the
# "Lookups (dynamic):" line of -bV output.  With SPF removed it must not.
if $exim -bV | grep -iE 'Lookups \(dynamic\):.*\bspf\b'; then
	echo "FAIL: exim still advertises SPF as a dynamic lookup"
	exit 1
fi

# --- 3. The _HAVE_SPF build macro must be undefined. ------------------------
# It is only predefined when SUPPORT_SPF is set; config using
# ".ifdef _HAVE_SPF" therefore degrades gracefully.  When the macro is
# undefined exim prints "macro _HAVE_SPF not found"; when it is defined it
# prints the macro's value instead.  So the failure case is the *absence*
# of the "not found" message.
if $exim -bP macro _HAVE_SPF 2>/dev/null | grep -qv 'not found'; then
	echo "FAIL: the _HAVE_SPF macro is still defined"
	exit 1
fi

# --- 4. The SPF module object must not be shipped anywhere. -----------------
if find /usr/lib/exim4 -name 'spf_miscmod.so' 2>/dev/null | grep -q .; then
	echo "FAIL: spf_miscmod.so is still installed"
	exit 1
fi

echo "PASS: SPF is disabled and exim4 is unaffected"
