#!/bin/sh

usage () {
	cat << EOT

Usage: $0 {on|off|folder|status}

This program controls what is done to messages received on your personal
account that are identified to be spam.  Note that this is only a helper
script that modifies your .procmailrc file.

$0 on - throw all spam away.
$0 off - let spam messages through.
$0 folder [foldername] - put spam into mail folder 'foldername'.
   Default folder is 'spam-messages'.
$0 status - query the current status of spam blocking.

EOT
	exit
}

magic_begin="# BEGIN spamblock settings"
magic_end="# END spamblock settings"
procmailrc=$HOME/.procmailrc

purge_previous_settings () {
	tmpfile=$procmailrc.tmp
	touch $procmailrc
	sed -e "/$magic_begin/,/$magic_end/d" $procmailrc >$tmpfile && \
	mv -f $tmpfile $procmailrc
	rm -f $tmpfile
	if [ ! -s $procmailrc ]; then rm -f $procmailrc; fi
}

set_spam_destination () {
	cat >>$procmailrc << EOT
$magic_begin
:0
* ^X-[Ss]pam-[Ss]tatus: Yes
$1
$magic_end
EOT
}

if [ $# -le 0 ]; then usage; fi

case $1 in

ON|on)
purge_previous_settings
set_spam_destination devnull
cat << EOT

Please note that if your e-mail address is your contact information as
a state authority, it is illegal to categorically block e-mail to the
address, even if it's probably spam.  If this concerns you, please do
"$0 off" now.

Besides, some users seem to take e-mail trashing too lightly.  If you
use this setting, false positive messages are forever lost, period.
If you're worried about this, consider directing spam to a folder with
"$0 folder".  You have been warned.

EOT
;;
OFF|off)
purge_previous_settings
;;
FOLDER|folder)
folder=${2:-spam-messages}
purge_previous_settings
set_spam_destination $folder
;;
STATUS|status)
dest=`sed -ne "/$magic_begin/,/$magic_end/s/^[^ *#:].*/&/p" $procmailrc`
case $dest in
	devnull) echo "spamblock is on" ;;
	?*) echo "spamblock to folder $dest" ;;
	*) echo "spamblock is off" ;;
esac
;;
*)
echo "$0: unknown action: $1"
usage
;;

esac
