#!/bin/sh
# Copyright by Doug Muth (dmuth@ot.com) 1997
# This program is free for NON-COMMERCIAL use.
#     If you want to use it commercially, please contact me, I'll be happy
#     to work out an agreement.

# This shell script is used as a "frontend" for running fetchmail.  It will
#	start up fetchmail and save the session to disk, generate statistics
#	of the e-mail that you downloaded, and tell you how many messages
#	you have in various folders.  A copy of these results are also
#	e-mailed to you.
#
#	Pre-requisites: You must have procmail, or at least `mailstat', a 
#		utility that comes with procmail, running on your system.
#		You must also have `timer', a shell script written by me, if
#		you would like the total time that the transfer took to be
#		displayed.

# Command line to run fetchmail
FETCHMAIL="/usr/local/bin/fetchmail $*"

# Your procmail logfile
LOG=$HOME/procmail/log

# Do we want to use timer?  Set to 0 to disable.
TIMER=1

# The temp file, and ensure my privacy!
TMP=/tmp/fetchmail.sh.$$
touch $TMP
chmod 600 $TMP

# Trap errors
trap "rm -f $TMP; echo ""Exiting at user request"" ; \
test $TIMER -eq 1 && timer -stop -id $$ >/dev/null; exit 1" 2 3 4 15

# Our path to sendmail with parameters
SENDMAIL="/usr/bin/sendmail -oi -t"

# Who am I?
SELF="dmuth@ot.com"

# The folders that I should check for the number of messages
FOLDERS="$MAIL mail/virus-l mail/procmail-d mail/lists mail/spam.list \
mail/fight-censorship"

# Number of seconds to "sleep" for while procmail finishes up
LATENT=10

# Fetchmail's exit code
EXIT_CODE=0

num_mail()
{ # This procedure tells me how many messages there are in each folder
for D in $* 
do
	if test -f $D
	then
		echo "There are `frm $D |wc -l` messages in $D"
	fi
done
}

getmail()
{ # Fetch the mail!

test $TIMER -eq 1 && timer -start -id $$ -quiet

$FETCHMAIL
EXIT_CODE=$?

# pause for a short while
echo "Now sleeping for $LATENT seconds..."
echo "Zzz...Zzz...Zzz..."
sleep $LATENT
}

stats()
{ # Prepare the statistics

test ! -e $LOG && touch $LOG  # Ensure we have a log file

echo -e "\n\t\t\t   Fetchmail Statistics"
mailstat -k <$LOG
echo ""
num_mail $FOLDERS
test $TIMER -eq 1 && echo -e "\n`timer -stop -id $$ -quiet` have elapsed."
echo -e "\nFetchmail's exit code was: $EXIT_CODE\n"
}

prepmail()
{ # Let's prepare our e-mail
cat <<EOF >$TMP
From: $LOGNAME (Fetchmail)
To: $LOGNAME
X-Loop: $SELF
Subject: Mail stats from `date "+%D %X"`

EOF
}

### Main Program

# let's have some initial cleanup
rm -f $LOG
clear

prepmail

getmail $* 2>&1 |tee -a $TMP
clear
stats $* 2>&1 |tee -a $TMP

# now send it and clean up the mess
cat $TMP |$SENDMAIL
rm -f $TMP

# cleanup the log file for next time
rm -f $LOG
