#!/bin/bash
#Copyright 2003 William Stearns <wstearns@pobox.com>
#Released under the GPL.
Version=0.1
echo "replace_blacklist version $Version"
echo "http://www.stearns.org/sa-blacklist"

requireutil () {
	while [ -n "$1" ]; do
		if ! type -path "$1" >/dev/null 2>/dev/null ; then
			echo Missing utility "$1". Please install it. >&2
			return 1        #False, app is not available.
		fi
		shift
	done
	return 0        #True, app is there.
} #End of requireutil

requireutil basename cat grep mktemp rm rsync sed || exit 1

if [ -z "$1" ] || [ -z "$2" ]; then
	cat <<EOF
This program replaces (or adds, if none existed previously) the manual blacklist in the listed spamassassin configuration files.

Syntax:

$0 /path/to/local_blacklist_copy /path/to/sa-config-file [sa-config-file] [sa-config-file]

Suggested usage:

$0 ~/sa-blacklist /etc/mail/spamassassin/local.cf /root/.spamassassin/user_prefs /home/anotheruser/.spamassassin/user_prefs ...

or add this to /var/spool/cron/root (changing the minute (17) so not everyone comes in at once):

17 1,7,13,19 * * * $0 /root/sa-blacklist /etc/mail/spamassassin/local.cf /root/.spamassassin/user_prefs /home/anotheruser/.spamassassin/user_prefs ...

and restart cron.  Feel free to use a non-privileged user to run this, as long as that user can write to all sa-config files.
EOF
	exit 1
fi
Blacklist="$1"
shift

if ! rsync -aqL zaphod.stearns.org::wstearns/sa-blacklist/sa-blacklist.current "$Blacklist" ; then
	echo rsync failed.
	if [ -s "$Blacklist" ]; then
		echo "$Blacklist exists, but may be outdated.  Proceeding anyways, but please find out why rsync failed."
	else
		echo "$Blacklist does not exist or is zero length.  Aborting."
		exit 1
	fi
fi

if [ -n "`cat $Blacklist | sed -e 's/#.*//' -e 's/^blacklist_from[ A-Za-z_\.\*@0-9\-]*//' | grep -v '^$'`" ]; then
	echo "The downloaded blacklist files has lines with content other than"
	echo "blacklist_from email_regex and comments.  Please take a look at $Blacklist"
	echo "and get a new version of this script.  Exiting."
	exit 1
fi

while [ -n "$1" ]; do
	if [ ! -w "$1" ]; then
		echo "$1 does not exist or is not writable, exiting."
		exit 1
	fi

	TmpFile=`mktemp -q "/tmp/$(basename $0).XXXXXX"`
	if [ $? -ne 0 ]; then
		echo "$0: Can't create temp file, exiting..."
		exit 1
	fi

	cat "$1" >$TmpFile
	( cat "$TmpFile" | sed -e '/#### Start of Manual Blacklist ####/,/#### End of manual blacklist ####/{d;}' ; cat "$Blacklist" ; echo ) >"$1"

	#Comment the next line if you're trying out the script and want to leave a copy of the original file in /tmp
	rm -f "$TmpFile"
	shift
done