#!/bin/bash

tmp1="/tmp/t1.$$"
tmp2="/tmp/t2.$$"
tmp3="/tmp/t3.$$"
tmp4="/tmp/t4.$$"
tmp5="/tmp/t5.$$"
log="/var/log/spam.log"
mail="0"

while [ "$1" != "" ]; do
	case $1 in
		-mail)
			mail="1"
		;;
		-log)
			shift
			log="$1"
		;;
		*)
		;;
	esac
	shift
done

stripsyslogentries()
{
	while read a b c d e f g h i j; do echo "$f $g $h $i $j"; done
}

sortbyto()
{
	awk '{print $4}' | sed -e's/<//' -e's/>$//' -e's/[ 	]//g' -e'/^$/d' | sort -u | { while read a; do echo -e "$a"; done; }
}

sortbyfrom()
{
	awk '{print $3}' | sed -e's/<//' -e's/>$//' -e's/[ 	]//g' -e'/^$/d' | sort -u | { while read a; do echo -e "$a"; done; }
}

filterbysender()
{
	while read a b c d e; do
		if [ "$c" = "$1" ]; then
			echo "$a $b $c $d $e"
		fi;
	done
}

filterbyrcpt()
{
	while read a b c d e; do
		if [ "$d" = "$1" ]; then
			echo "$a $b $c $d $e"
		fi;
	done
}

# for each of the addresses, create a hit list
rptaddresses()
{
	while read a; do
		cat $1 | filterbysender "<$a>" > $2
		echo -e "\t`cat $2 | wc -l | sed -e's/ //g'` - $a"
		cat $2 | sortbyto | { while read b; do echo -e "\t\t$b"; done; }
	done
}

# for each of the addresses, create a hit list
senderaddresses()
{
	while read a; do
		cat $1 | filterbyrcpt "<$a>" > $2
		echo -e "\t`cat $2 | wc -l | sed -e's/ //g'` - $a"
		cat $2 | sortbyfrom | { while read b; do echo -e "\t\t$b"; done; }
	done
}

cat $log | grep -v newsyslog | stripsyslogentries > $tmp1

# report statistics
for rpt in Accepted Rejected Spam Discarded RcptVerify; do
	echo -e "--- total $rpt ---" >> $tmp5
	grep \^$rpt $tmp1 | tee $tmp2 | wc -l | sed -e's/ //g' >> $tmp5
	if [ $rpt == "Discarded" ]; then
		echo -e "\t--- by sender ---" >> $tmp5
		cat $tmp2 | sortbyfrom | rptaddresses $tmp2 $tmp3 >> $tmp5
	else
		echo -e "\n\t--- by recipient ---" >> $tmp5
		cat $tmp2 | sortbyto | senderaddresses $tmp2 $tmp3 >> $tmp5
	fi
	echo -e "\n\n" >> $tmp5
done

if [ "$mail" = "0" ]; then
	cat $tmp5
else
	cat $tmp5 | mail -s "Wan2 Email/Spam Log report" root
fi

rm -f $tmp1 $tmp2 $tmp3 $tmp4 $tmp5
