#! /bin/bash

echo
echo "# **********************************************"
echo "# register any messages left in unsureCur as spam"
echo "# then move those Spam messages to the spam folder"
echo "#"
echo "# this script was written for a user Maildir folder"
echo "# using debian exim4, dovecot, maildrop and bogofilter"
echo "# filtering Spam and more in a user .mailfilter file"
echo "# **********************************************"
echo

startSec="$(date +%s)"
startDate="$(date)"

unsureDir="/home/gary/Maildir/.AUnsure"
unsureCur="/home/gary/Maildir/.AUnsure/cur"
unsureFiles="/home/gary/Maildir/.AUnsure/cur/*"
spamCur="/home/gary/Maildir/.Junk/cur/"

# fist, check to see if the unsureDir exists
if [ ! -d "$unsureCur" ]
then
    echo "The $unsureCur mail folder doesn't exist."
    echo "Check the bogospam.sh settings."
    echo
else
    # check to see if there are any files in unsureCur
    if [ -z "$(ls -A $unsureCur)" ]
    then
        # no files found
        echo "The $unsureCur mail folder is empty."
        echo "No messages for bogofilter to register."
        echo
    else
        # found file(s), register the text as spam
        echo "found message(s) in $unsureCur"
        echo "bogofilter registering Unsure as spam ..."
        echo
        echo "bogofilter command: bogofilter -v -l -s -I $unsureDir"

        # -v(vv..) = verbosity of report to std out
        # -l = write to syslog
        # -s = register text as spam
        # -I = dir to get text from
        # even though the files will be in the cur subdir,
        # bogofilter needs the unsure mail folder name one
        # level above that in order to find the messages.
        bogofilter -v -l -s -I "$unsureDir"
        echo "done"
        echo

        # next check to see that the spam folder exists
        # Although bogofilter will find messages in cur and new,
        # AFAICT the new dir is always empty, just move the
        # unsure files in the unsure cur dir
        if [ -d "$spamCur" ]
        then
            echo "The Spam folder is: $spamCur"
            echo "moving Unsure messages to Spam folder ..."
            mv $unsureFiles $spamCur
            echo "done"
            echo
        else
            echo "The Spam folder ($spamCur) doesn't exist."
            echo "Check the bogospam.sh settings."
            echo "bogospam can not move any messages."
            echo
        fi
    fi
fi

# calculate the end stats
endSec="$(date +%s)"
endDate="$(date)"
totalMin="$[(endSec-startSec)/60]"
totalSec="$[(endSec-startSec)%60]"

echo "********** bogospam is complete **********"
echo
echo "Start: $startDate"
echo "End:   $endDate"
echo "Total time (min:sec): $totalMin:$totalSec"
echo

exit 0
