#!/bin/sh
# $Id:$
# 
# Version: 1.0
#
# Copyright (C) 2010 Ola Lundqvist <ola@inguza.com>
# 
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301 USA.
#
# Changes:
#	2010-10-24 Ola Lundqvist <ola@inguza.com>
#		Basic implementation.
#	

CONFIGDIR=/etc/fanram
DATADIR=/var/lib/fanram
MAILTO=root
SUBJECT="fanram notification"
if [ -e "/etc/fanram/fanram.conf" ] ; then
    . /etc/fanram/fanram.conf
fi
if [ -e ~/.fanramrc ] ; then
    . ~/.fanramrc
fi
CONFIGS=$(find $CONFIGDIR -maxdepth 1 -type f ! -name "*~" -a ! -name "*.conf" -a ! -name "*.template")

fcompare() {
    TMPNAME=$1
    TMPNEW=$2
    TMPOLD=$3
    if [ -e "$TMPNEW" ] && [ ! -e "$TMPOLD" ] ; then
	echo "$TMPNAME is new"
	cp "$TMPNEW" "$TMPOLD"
    elif [ -e "$TMPNEW" ] && [ ! -e "$TMPOLD" ] ; then
	echo "$TMPNAME is removed"
	rm -f "$TMPOLD"
    elif [ -e "$TMPNEW" ] ; then
	TMPNEWMD=$(md5sum "$TMPNEW" | sed -e "s| .*||;")
	TMPOLDMD=$(md5sum "$TMPOLD" | sed -e "s| .*||;")
	if [ "$TMPNEWMD" != "$TMPOLDMD" ] ; then
	    echo "$TMPNAME is modified"
	    diff -u "$TMPOLD" "$TMPNEW"
	    cp "$TMPNEW" "$TMPOLD"
	fi
    fi
}

checkresource() {
    TMPRESOURCE=$1
    TMPRESCMP=$(echo "$TMPRESOURCE" | tr '/?&@' '_.,_')
    wget -q $TMPRESOURCE -O "$DATADIR/new-$TMPRESCMP"
    fcompare "$TMPRESOURCE" "$DATADIR/new-$TMPRESCMP" "$DATADIR/$TMPRESCMP" \
	>> $DATADIR/mail
    rm -f "$DATADIR/new-$TMPRESCMP"
}

checkfile() {
    TMPFILE=$1
    TMPFILECMP=$(echo "$TMPFILE" | tr '/?&@' '_.,_')
    fcompare "$TMPFILE" "$TMPFILE" "$DATADIR/$TMPFILECMP" \
	>> $DATADIR/mail
}

mkdir -p $DATADIR
touch $DATADIR/mail

for CONF in $CONFIGS ; do
    FILE=$(echo $CONF | sed -e "s|.*/||;")
    cat $CONF | while read LOCATION EXTRA ; do
	if echo $LOCATION | grep "^http://" > /dev/null ; then
	    checkresource $LOCATION
	elif echo $LOCATION | grep "^https://" > /dev/null ; then
	    checkresource $LOCATION
	else
	    checkfile $LOCATION
	fi
    done
done

if [ $(wc -l $DATADIR/mail | sed -e "s| .*||;") -gt 0 ] ; then
    cat $CONFIGDIR/email.template $DATADIR/mail | \
	mail -s "$SUBJECT" $MAILTO
fi
rm -f $DATADIR/mail
