#!/bin/sh

# Automatically create a list of domains that have SPF DNS RR enabled. Add the found domains
# to a file, which is used by exim to lookup SRS enabled domains.

SRS_FILE=/etc/exim4/srs_domains
EXIM_VDOM_FILE=/etc/exim4/virtual_domains
EXIM_PRIMARY_DOMAIN="ente.limmat.ch"


# This script might be called from /etc/default/bind to be included in bind's
# start-up script. So action "stop" shouldn't rebuild the srs_domains file.
if [ ! -z "$1" -a "$1" != "start" -a "$1" != "reload" -a "$1" != "restart" -a "$1" != "force-reload" ]; then
	exit 0
fi

# set tmp file for preparation
SRS_FILE_HOT="$SRS_FILE"
SRS_FILE="${SRS_FILE}_tmp"

# write file skeleton

template="# $SRS_FILE_HOT

# SRS enabled mail domains

# This auto generated file contains all SRS enabled mail domains of this host. It is generated by
# querying the DNS for all mail domains on $EXIM_PRIMARY_DOMAIN for an existing SPF entry.
# You may find the script here:
# $0

"
echo "$template" > "$SRS_FILE"


# process all mail domains
DOMLIST="$(echo "$EXIM_PRIMARY_DOMAIN")$(egrep -v "^[ #\t\*]+" "$EXIM_VDOM_FILE" | sed -e "s/^\(.*\):.*$/\1/")"

for dom in $DOMLIST; do
	# check domain for SPF RR
        if [ $(dig +noall +short $dom SPF | wc -m) -eq 0 ]; then
		# Domain has no SPF enabled
		continue;
        fi

	# add domain to srs_domains file
	echo "$dom" >> "$SRS_FILE"

done

# add footer
echo -e "\n\n# generated on: $(date +"%y-%m-%d %H:%M:%S") by $(basename $0)" >> "$SRS_FILE"

# move prepared file in place
sync
mv "$SRS_FILE" "$SRS_FILE_HOT"
