#!/bin/sh
#
#spambuild v0.1 9 September 2006
#Copyright Charles J Mitchell <cmitchell@whitehat-inc.com>
#Scripts are necesarrily Open Source

#This file should reside in /usr/local/sbin
#This program is for use with sendmail
#It does not work with any other MTA

#Files

#Access file
ACCESS="/etc/mail/access"

#Blacklist
BLACKLIST="/etc/mail/access.blacklist"
BLACKLISTLOCAL="/etc/mail/access.blacklist.local"

#Whitelist
WHITELIST="/etc/mail/access.whitelist"
WHITELISTLOCAL="/etc/mail/access.whitelist.local"

#Network Ranges
RANGE="/etc/mail/access.netrange"
RANGELOCAL="/etc/mail/access.netrange.local"

#Error message file
ERROR="/etc/mail/access.error"

#Tmp file
TMP=`mktemp /tmp/spambuild.XXXXXX`

###########################################################
#Begin processing here
trap "/bin/rm -f $TMP" 1 2 3 6 15

if [ -f /etc/mail/access.error.local ]; then
	E=`cat /etc/mail/access.error.local`
else
	E=`cat /etc/mail/access.error`
fi

#Init
echo "#access file built by spambuild v0.1" > $TMP
echo >> $TMP

#Put local whitelist entries in tmp
echo "#local whitelist" >> $TMP
echo >> $TMP

if [ -f $WHITELISTLOCAL ]; then

	LIST=`cat $WHITELISTLOCAL | awk '{print $1}'`

	for i in $LIST; do
		echo "$i		OK" >> $TMP
	done

	echo >> $TMP
fi

#Put local blacklist entries in tmp
echo "#local blacklist" >> $TMP
echo >> $TMP

if [ -f $BLACKLISTLOCAL ]; then

	LIST=`cat $BLACKLISTLOCAL | awk '{print $1}'`

	for i in $LIST; do
		echo "$i		$E" >> $TMP
	done

	echo >> $TMP
fi

#Put local range entries in tmp
echo "#local network range list" >> $TMP
echo >> $TMP

if [ -f $RANGELOCAL ]; then

	LIST=`cat $RANGELOCAL | awk '{print $1}'`

	for i in $LIST; do
		echo "$i		$E" >> $TMP
	done

	echo >> $TMP
fi

#Put whitelist entries in tmp
echo "#whitelist" >> $TMP
echo >> $TMP

if [ -f $WHITELIST ]; then

	LIST=`cat $WHITELIST | awk '{print $1}'`

	for i in $LIST; do
		echo "$i		OK" >> $TMP
	done

	echo >> $TMP
fi

#Put blacklist entries in tmp
echo "#blacklist" >> $TMP
echo >> $TMP

if [ -f $BLACKLIST ]; then

	LIST=`cat $BLACKLIST | awk '{print $1}'`

	for i in $LIST; do
		echo "$i		$E" >> $TMP
	done

	echo >> $TMP
fi

#Put range entries in tmp
echo "#Blocked network range list" >> $TMP
echo >> $TMP

if [ -f $RANGE ]; then

	LIST=`cat $RANGE | awk '{print $1}'`

	for i in $LIST; do
		echo "$i		$E" >> $TMP
	done

	echo >> $TMP
fi

#Put tmp into access file
cat $TMP > $ACCESS

#Restart sendmail/rebuild dbfile

cd /etc/mail
make *.db > /dev/null

#Cleanup
rm -f $TMP






