#!/bin/sh

folders="SPAM HAM"

for AM in $folders
do 
  am=`echo $AM | tr A-Z a-z`
  echo "> Processing '$AM' with sa-learn flag '--$am'"
  for dir in `find /var/spool/cyrus/mail/*/user/*/$AM -prune -maxdepth 1`
  do
    user=`echo $dir | awk -Fuser/ '{print $2}' | awk -F/$AM '{print $1}'`
    echo ">> User: $user"

    ## Send 
    echo ">>> Learn: '$dir'"
    su - cyrus -c "sa-learn --$am --showdots $dir/*."

    ## Send each spam message through spamfirewall for blocking
    echo ">>> Block: Firewalling offending spam mail servers"
    for message in `find $dir/*. -prune -maxdepth 1`
    do
      #echo ">>> Block: '$message'"
      cat $messge | /usr/local/bin/spamfirewall 1 
    done

    ## Purge all the users spam messages after they have been learned from
    echo ">>> Purge: 'user.$user.$AM'"
    #su - cyrus -c "/usr/sbin/ipurge -f -d 0 user.$user.$AM"
    su - cyrus -c "/usr/sbin/ipurge -f -b 0 user.$user.$AM"
  done
done  

