#!/bin/sh
# mailann v1.0 by msittig (16jan2002)
# Simple script to check the .procmail.log file for new mail,
# and print details to the terminal.
# Set this script to run each time a user logs in. 
# Please mail comments to takoyaki@ugcs.caltech.edu
# 
# Much love to
# Script:	nm
# Author: 	Duncan Potter, EUCS, May 1997

# Script takes mailbox names as arguments to scan for in the procmail
# log (assumes mailboxes are in $HOME/Mail/

# Initialize the message holder
MSGS=0

if [ ! -f "$HOME/.auditlog" ]; then
# Perform logical test on existance of "auditlog", TRUE if it exists.
	touch $HOME/.auditlog
	echo "No new mail for $USER."
	exit 1
# Logically, no mail existed so echo the message and exit
fi

if [ ! -f "$HOME/.auditlog-comp" ]; then
    touch $HOME/.auditlog-comp
# The procmail comprehensive log did not exist
# so it was created by 'touch'
fi

# Concatenate the contents of procmail log onto the comprehensive
# log; we are now free to destroy the log (muahaha)
cat $HOME/.auditlog >> $HOME/.auditlog-comp

# Perform logical test on size of logfile, TRUE if non-zero size.
# If TRUE, there is new mail.
if [ -s $HOME/.auditlog ]; then

# Scan procmail log for lines containing Folder: and filter out
# messages sent to /dev/null
    MSGS=$(cat $HOME/.auditlog | awk '/Folder:/ {print $2}' | sed -e '/dev\/null/ d')

# For each argument (mailboxes) check for existance in MSGS message log
# and count how many times.  Used tr to change MSGS into a multi-line argument
# for grep.  Storing multi-line string in MSGS seems to remove the newlines.
    while [ $# -gt 0 ]
    do
	NUMBER=$(echo $MSGS | tr " " "\n" | grep -c $1)

# Echo appropriate message for number of e-mails forwarded to the mailbox
	case $NUMBER in
	    0)  ;;
	    1)  echo "$NUMBER message in $1" ;;
	    *)  echo "$NUMBER messages in $1" ;;
	esac
	cat $HOME/.auditlog | grep -B 2 $1 | awk '/From/ {LAST=$0} /Subject/ {print LAST, $0}' | awk '/From/ {if ($12) print "   ->", $9, $10, $11 "... (" $2 ")"; else print "   ->", $9, $10, $11, "(" $2 ")";}'p
#	cat $HOME/.auditlog | tr " " "\n" | awk '/Subject:/ {print $2}'
#	cat $HOME/.auditlog | grep -B 2 $1 | awk '/Subject:|From/ {print $0}' | tr " " "\n" | awk '/From/ {print ", $9, $10, $11}'
#	sed -e 's/From/  From/' -e 's/Subject/   Subject/'
    shift
    done

    if [ -n MSGS  ]
    then
        GARBAGE=1
    else
	echo "No new messages in other mailboxes."
	exit 1
    fi

    rm $HOME/.auditlog
    touch $HOME/.auditlog

else 
    echo "No new messages in other mailboxes."
fi

# Exit properly
exit 1
