import EXT
import HOST
VPOPMAILDIR="/home/vpopmail"
VHOME=`$VPOPMAILDIR/bin/vuserinfo -d $EXT@$HOST`
DOMDIR=`$VPOPMAILDIR/bin/vdominfo -d $HOST`
NOEXT=`echo $EXT | awk -F- '{ print $1}'`
JUNK="$VHOME/Maildir/.Junk/"
DELETESCORE=100


DUMMY=`test -d $VHOME/Maildir`
if ( $RETURNCODE == 1 )
{
    DUMMY=`test $EXT = $NOEXT`
    if ( $RETURNCODE == 1 )
    {
        VHOME=`$VPOPMAILDIR/bin/vuserinfo -d $NOEXT@$HOST`
    }
}

DUMMY=`test -d $VHOME/Maildir`
if ( $RETURNCODE == 1 )
{
	DUMMY=`grep bounce-no-mailbox $DOMDIR/.qmail-default`
	if ( $RETURNCODE == 0 )
	{
   		echo "Sorry, no mailbox here by that name. (#5.1.1) - maildrop"
   		EXITCODE=100
   		exit
	}
	DUMMY=`grep ' delete$' $DOMDIR/.qmail-default`
	if ( $RETURNCODE == 0 )
	{
   		echo "Deleted mail for non-existent user $EXT@$HOST - maildrop"
   		EXITCODE=0
   		exit
	}
	# else, it's either a Maildir or forward
	ARG4=`awk '{ print $4 }' $DOMDIR/.qmail-default`
	# check forward first
	DUMMY=`echo $ARG4 | grep '@'`
	if ( $RETURNCODE == 0 )
	{
		to '| /var/qmail/bin/qmail-inject'
	}
	# then check Maildir
	DUMMY=`echo $ARG4 | grep '^/'`
	if ( $RETURNCODE == 0 )
	{
		VHOME="$ARG4"
		JUNK="$ARG4/Maildir/.Junk/"
	}
}


# pipe to spamc
if ( $SIZE < 262144 )
{
        exception {
                xfilter "/usr/bin/spamc -f -u $EXT@$HOST"
        }
}

if (/^X-Spam-Flag: *YES/)
{
        exception {
		/X-Spam-Status: Yes, score=!-*[0-9]+\.[0-9]+/
		SCORE=$MATCH2
		if ($SCORE >= $DELETESCORE )
		{
			if ( /^From: *!.*/ )
			{
   				ADDR=getaddr($MATCH2)
			}

        		echo "auto-deleted spam from $FROM::$ADDR to $EXT@$HOST with score of $SCORE"
			to /dev/null
		}
        }

	# check for junk folder, create and subscribe if necessary
        DUMMY=`test -d $JUNK`
        if ( $RETURNCODE == 1 )
        {
                `/var/qmail/bin/maildirmake $JUNK`
                `touch $JUNK/maildirfolder`
                `chown vpopmail:vchkpw  $JUNK/maildirfolder`
                DUMMY=`grep $JUNKNAME $VHOME/Maildir/courierimapsubscribed`
                if ( $RETURNCODE == 1 )
                {
                        `echo $JUNKNAME >> $VHOME/Maildir/courierimapsubscribed`
                        `chown vpopmail:vchkpw $VHOME/Maildir/courierimapsubscribed`
                }
                echo "created $JUNK"
        }

        echo "maildrop: filtered junk from $FROM::$ADDR to $EXT@$HOST with score of $SCORE"
        to $JUNK
}
else
{
	# optionally include other filter instructions
	DUMMY=`test -f $VHOME/.mailfilter`
	if ( $RETURNCODE == 0 )
	{
		include $VHOME/.mailfilter
	}
	echo "maildrop: non-filtered mail delivery"
        to $VHOME/Maildir/
}
