#!/bin/sh --

#
# roessler@guug.de, Thu, 18 Feb 1999 13:45:01 +0100
#
# Distribute and use freely.
#

MUTT="/usr/local/bin/mutt -F /dev/null"
MUTT_DOTLOCK=/usr/local/bin/mutt_dotlock
WGET=/usr/bin/wget
LYNX=/usr/bin/lynx
MD5SUM=/usr/bin/md5sum

umask 077

RCFILE=$HOME/.webmind
WKDIR=${TMPDIR-/tmp}/`basename $0`.$$

trap "trap '' 0 ; /bin/rm -rf $WKDIR ; $MUTT_DOTLOCK -u $RCFILE; exit" 0 1 2 3

mkdir $WKDIR || { echo "couldn't create tempdir" >&2 ; exit 1; }
cd $WKDIR

$MUTT_DOTLOCK $RCFILE || { echo "couldn't lock $RCFILE" >&2 ; exit 1; }

egrep -v '^#|^$' $RCFILE | while read LINE ; do
	set - $LINE
	ADDR=$1
	FMT=$2
	URL=$3
	MD5=$4

	rm -f $WKDIR/tmp.html $WKDIR/tmp2.html $WKDIR/tmp.txt
	if $WGET -q -Y off -O $WKDIR/tmp.html "$URL" ; then
	  	NEW_MD5=`$MD5SUM $WKDIR/tmp.html | awk '{print $1}'`

		echo "<BASE HREF=\"$URL\">" | cat - $WKDIR/tmp.html > $WKDIR/tmp2.html
	  	if test \( ! "$MD5" = "." \) -a \( ! "$NEW_MD5" = "$MD5" \) ; then
	  		if test "$FMT" = "txt" ; then
				$LYNX -dump $WKDIR/tmp2.html > $WKDIR/tmp.txt
				ATTACH=$WKDIR/tmp.txt
			else
				ATTACH=$WKDIR/tmp2.html
			fi
			$MUTT -a $ATTACH -s "`basename $0`: $URL has changed." $ADDR << EOM
Hi, this is `basename $0` on $HOSTNAME speaking.

I just noticed that the web page under 
$URL
has changed, and my configuration says
I should tell you about it.

You can find the new page contents in the
attachment.
EOM
		fi
		MD5="$NEW_MD5"
	fi
	
	echo "$ADDR $FMT $URL $MD5" >> $WKDIR/webmind.tmp
done

mv $WKDIR/webmind.tmp $RCFILE

exit 0

