#! /bin/csh  

#  H.A. Trujillo, 12 Sept 11
#
#  29 Jan 12:	message-splitter converted from formail to awk
#		"=foo" support added
#
#  30 Sep 12:	subject line of spam-laden messages printed
#
#  18 Nov 12:	output formatting tweaked
#
#  08 Jan 15:  can now deal with null ("<>") envelope sender


if ( $1 == -h ) then 
    tr \# ' ' << EOT
    #
    #  Check the contents of a mailbox for messages containing a virus or
    #  malware and specify which messages are bad.
    #
    #  USAGE:   malwarecheck <file>
    #		    "=foo" notation for "~/Mail/foo" is supported
    #
EOT
    exit
endif

set esc = `printf \\033`

set mailbox = "$1:s,=,~/Mail/,"
#	sanity check
if ( ! -e $mailbox ) then
    echo "${0:t}: File ${esc}[4m${mailbox}${esc}[m not found"
    exit 1
endif


@ len = `echo $1 | wc -c`	# length of filename

#	split mailbox into individual messages
set dir = /tmp/split_msgs.$$
mkdir $dir
cat $mailbox \
    | awk '/^From .*(@|<>).*:..:.. /{ close("'$dir/'"n); n += 1 } ;\
	  { print $0 > ("'$dir/'"n) }' 


printf "\nMessages in $1 flagged by clamd:  \n\n"

clamdscan /tmp/split_msgs.$$ | sed -E 's,/tmp/split_msgs[^/]+/,,' > /tmp/infected_msg_list.$$


set bad_msg_nbr = (`cat /tmp/infected_msg_list.$$ | grep FOUND | cut -f1 -d:`)
if ("$bad_msg_nbr" == "" ) then
    echo "                                ${esc}[${len}C${esc}[2A none ${esc}[1B" 
  else
    cd $dir
    @ i = 0
    foreach file ($bad_msg_nbr)
	@ i++
	printf %s  "  " $bad_msg_nbr[$i] ":	"
	grep  "^Subject:" $file | cut -f2- -d:
    end
    printf "\n  Remember to set Mutt sorting to U when deleting.\n"
  endif

\rm -r /tmp/split_msgs.$$ /tmp/infected_msg_list.$$

