#!/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

realmsdir='/etc/local-REDPILL'
domainconfdir='/etc/local-ORG/amavis'
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 /etc/local-ORG/realm || dnsdomainname | tr '[a-z]' '[A-Z]')"

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

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

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

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

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