#!/bin/sh
#####
## Simple script to do mail filtering with bounce or local delivery option
# Rev 0.9
# By: Laird Bedore
# Date: 2/13/03
#####
## The following variables are read from the config file
#   BOUNCE
#   DELIVER
#   SPAMFOLDER
#   REWRITE_SUBJ
#####
## This is the embedded perl code to do the actual delivery to the mailbox
# Syntax:
#   echo "$output" | perl -e "$PERLCODE" ~/.mail/$SPAMFOLDER;ret=$?

PERLCODE="
\$f=\$ARGV[0]; 
open(M,\">>\$f\") or exit 255;
while (\$ct<5) {
 if (flock(M,6)) {
  seek(M,0,2); \$l=<STDIN>;
  while (defined(\$l)) {
   print M \$l; \$l=<STDIN>;
  } print M \"\n\";
  flock(M,8); close(M); exit 0;
 } \$ct++; sleep 1;
} close(M); exit -1;"

#####
## Read the user's config file
if [ -f ~/.mailfilter.conf ]; then
  . ~/.mailfilter.conf
else
  # No mailfilter.conf - do not filter, just pass through
  echo "`date -R`: user=`whoami` conffile error: file not found" >> /var/log/mailfilter.log
  exit 0
fi

#####
## Grab the STDIN and add a From line, so it's a standard mail
output="From $SENDER `date -u \"+%a %b %d %T %Y\";cat`"
#####
## Execute the filter check.
`echo $output|grep -i -f .mailrules &>/dev/null`
exitcode=$?

if [ $exitcode == 0 ]; then
  if [ $BOUNCE == 1 ]; then
    echo "Email rejected: spam mail is not allowed here!"
echo "`date -R`: user=`whoami` debug: bouncing an email." >> /var/log/mailfilter.log
    # exit for a bounce
    exit 100
  elif [ $DELIVER == 1 ]; then
    if [ $REWRITE_SUBJ == 1 ]; then
      output="`echo \"$output\"|sed -e \"s/^Subject: /Subject: (SPAM) /\"`"
echo "`date -R`: user=`whoami` debug: rewriting an email header before delivery." >> /var/log/mailfilter.log
    fi
    if [ ! -f .mail/$SPAMFOLDER ]; then
echo "`date -R`: user=`whoami` debug: in delivery, spamfolder not found. default to inbox." >> /var/log/mailfilter.log
      SPAMFOLDER="INBOX"
    fi
    # Execute delivery of the message!
    err=`echo "$output" | perl -e "$PERLCODE" ~/.mail/$SPAMFOLDER 2>&1`;ret=$?
    if [ $ret == 0 ]; then # Success
echo "`date -R`: user=`whoami` debug: successful alternate delivery done." >> /var/log/mailfilter.log
      exit 99
    elif [ $ret == 255 ]; then
      echo "`date -R`: user=`whoami` perl error: $err" >> /var/log/mailfilter.log
      exit 99
    else # Temp failure - probably a file locking problem. deliver later.
      echo "`date -R`: user=`whoami` temporary delivery error: $err" >> /var/log/mailfilter.log
      exit 111
    fi
  else #if neither bounce nor deliver... drop!
echo "`date -R`: user=`whoami` debug: matched msg. neither bouncing nor delivering. dropped." >> /var/log/mailfilter.log
    exit 99
  fi #if bounce or deliver
else #exitcode - not a spam match - just deliver
echo "`date -R`: user=`whoami` debug: msg checked. Not matched as spam." >> /var/log/mailfilter.log
  exit 0
fi

### End of File.
