#!/bin/bash
# This script will take care to download the latest ical
# calendar I might have pushed using other tools, such as KDE's
# groupware suite. (Kontact and friends).

ICALPATH="/Users/your_account/Library/Application Support/iCal/Sources/YOUR-SOURCE-FOLDER"
WEBDAV="http://www.yourserver.com/path/to/dav/folder/calendar.ics"
LOGIN="yourlogin"
PASSWORD="yourpassword"

WGET="/sw/bin/wget"
MD5SUM="/sw/bin/md5sum"

## Internal Values. Change not.
NEWCAL="cal_download.ics"
OLDCAL="corestorage.ics"

echo "Downloading calendar from WebDAV server..."
if [ -d "$ICALPATH" ] ; then
	cd "$ICALPATH"
else
	echo "Sorry! You got the ical core storage folder wrong!"
	exit 1
fi

$WGET -c --http-user=$LOGIN --http-password=$PASSWORD $WEBDAV -O $NEWCAL

if [ $? -eq 0 ] ; then
	# Download apparently completed. Let's check the file, roughly
	echo "Checking for ICS format..."
	cat $NEWCAL | grep "END:VCALENDAR"
	if [ $? -ne 0 ] ; then
		echo "Sorry, this file is apparently wrong. Maybe it's a fancy 404" 
		echo "or the file got mangled. Check your settings."
		echo "Removing temporary files..."
		rm -f $NEWCAL
		exit 1
	fi
	
	LOCALSUM=`$MD5SUM $OLDCAL | cut -d ' ' -f 1`
	REMOTESUM=`$MD5SUM $NEWCAL | cut -d ' ' -f 1`
	
	if [ $LOCALSUM = $REMOTESUM ] ; then
		echo "Files are identical. Nothing to do."
		echo "Phew, glad this went well."
		echo "Removing temporary files..."
		rm -f $NEWCAL
		exit 0
	else
		echo "Updating local ical..."
		cp -f $OLDCAL $OLDCAL.old
		mv -f $NEWCAL $OLDCAL
		echo "Done! Phew, glad this is over."
	fi
else
	echo "Download crapped out. Exiting..."
	exit 1
fi
		
