#!/bin/sh
#
# /etc/local-COMMON/amavis/mklists.sh
# Copyright 2007 Jonas Smedegaard <dr@jones.dk>
#
# $Id: mklists.sh,v 1.3 2007-10-19 01:14:22 jonas Exp $
#
# Resolve own mail domains and MX backup domains

set -e

# Let's standardize sort
export LC_ALL=C

basedir=${basedir:-/etc}
REDPILL=${REDPILL:-REDPILL}
ORG=${ORG:-ORG}
realmsdir=${realmsdir:-$basedir/local-$REDPILL}
domaindir=${domaindir:-$basedir/local-$ORG}
domainconfdir=${domainconfdir:-$domaindir/amavis}
localdir=${localdir:-$basedir/local}
if ! [ -d "$realmsdir" ]; then
	echo "WARNING: Realms directory \"$realmsdir\" does not exist."
fi
if ! [ -d "$domainconfdir" ]; then
	echo "WARNING: Domain config directory \"$domainconfdir\" does not exist."
fi

catfilefromownrealm() {
	file="$1"
	[ -d "$realmsdir" ] || exit 0

	thisrealm="$(cat "$domaindir/realm" || dnsdomainname | tr '[a-z]' '[A-Z]')"

	if [ -r "$localdir/${file}_exceptions" ]; then
		grep -vFf "$localdir/${file}_exceptions" "$realmsdir/$thisrealm/$file"
	else
		cat "$realmsdir/$thisrealm/$file"
	fi
	if [ -r "$localdir/${file}_additions" ]; then
		cat "$localdir/${file}_additions"
	fi
}

catallfilesfromotherrealms() {
	file="$1"
	[ -d "$realmsdir" ] || exit 0
	[ -f "$realmsdir/realms" ] || exit 0

	realms="$(cat "$realmsdir/realms" | sed 's/#.*//')"
	thisrealm="$(cat "$domaindir/realm" || dnsdomainname | tr '[a-z]' '[A-Z]')"

	for realm in $realms; do
		if [ "$thisrealm" != "$realm" ]; then
			if [ -r "$localdir/${file}_additions" ]; then
				grep -vFf "$localdir/${file}_additions" "$realmsdir/$realm/$file"
			else
				cat "$realmsdir/$realm/$file"
			fi
		fi
	done
	if [ -r "$localdir/${file}_exceptions" ]; then
		cat "$localdir/${file}_exceptions"
	fi
}

catfilefromownrealm maildomains | sort > "$domainconfdir/local_domains"
catallfilesfromotherrealms maildomains | sort > "$domainconfdir/nonlocal_domains"