#!/bin/bash 

. ~/.profile.common

# first check to see if a sync is already going on.  if it is, we do NOT
# want to sync calendars. 
SYNC=/dev/ttyUSB1
if [ -e "$SYNC" ]
then 
	SYNCING=1
else
	SYNCING=0
fi

if [ "$SYNCING" -eq 1 ]
then
	echo "detected syncing going on.  not going to update calendar now."
	exit 5
fi

# pidfile...
PIDFILE="/tmp/exchange_calendar_1way_sync.pid"

if [ -f "$PIDFILE" ]
then
	echo "previous pidfile found."
	PID=$(cat $PIDFILE)
	COUNT=$(ps -aef | grep $PID | grep -v grep | wc -l)
	if [ $COUNT -gt 0 ]
	then
		echo "found: [$COUNT] processes running with that pid."
		echo "not running."
		exit 6
	else
		echo "no processes found for pid: [$PID]. continuing."
	fi
fi

# SAVE off our pid
echo "$$" > "$PIDFILE"

# should we be verbose with debugging?
DEBUG=0

#   Order of business:

# - First, we retrieve the exchange calendar with owaSync, which puts all
#   our calendar events into individual .ics files.

# - Second, we go through our retrieved exchange calendar ics-files and
#   remove the END:VCALENDAR, BEGIN:VCALENDAR tags so that we can merge all
#   of these events into a single .ics file.  We also need to create our
#   own UID field, replacing the very long one we get from Exchange with an
#   md5sum of it.  This is so that our UID line doesn't get truncated as a
#   result of being so long.  We also mark each of these events as being
#   from a WorkXChange CATEGORY so that we can find these events later.
#   Since CATEGORIES will sync to our palm pilot, we'll be assured that
#   this data will persist across hotsyncs.

# - Third, we iterate through each of these files and see if we can find
#   them in our korganizer calendar file.  If we've synced these records
#   before, we need to make sure that we keep the same X-PILOT-ID values
#   (and anything else that needs to be the same across syncs).  If we can
#   find them (we'll look to identify them by their UID which we've changed
#   above to be the md5sum of the MD5SUM line), then inject the values from
#   korganizer's std.ics file into this event file.

# - Fourth, go through korganizer's std.ics file and remove any and all
#   VEVENTS that we previously put there (from our exchange calendar).  We
#   will identify these records by having CATEGORIES:WorkXChange.  Wipe
#   them out, all of them.

# - Fifth, take off the ending vcalendar tag from korganizer's ics-file,
#   bring all of our exchange calendar events into it, and then tack on the
#   ending tag.

XCAL="${HOME}/exchange_calendar.ics"
XEVENTS="${HOME}/exchange_calendar.events"

MERGECAL="${HOME}/.kde/share/apps/korganizer/std.ics"
#MERGECAL="${HOME}/test-korganizer-std.ics"

# back it up!!!
cp "$MERGECAL" "$MERGECAL.$(date +'%Y%m%d%H')"

echo "working on file: [$MERGECAL]"

WORKFILE="/tmp/temp_korg_cleanup.ics"


# -- start of functions...

function cleanupIncomingFile
{
	FILE="$1"

	# make sure we have a newline on the end of the file, dangit
	echo "" >> "$FILE"

	# create a shortened form of the UID--guaranteed to be unique by
	# being an md5sum. only md5sum the UID, not the "UID:" tag...
	MD5UID=$(grep "^UID:" "$FILE" | tail -1 | cut -d ":" -f2 | md5sum | awk '{print $1}')

	# grab the old UID 
	OLDUID=$(grep "^UID:" "$FILE" | tail -1 | cut -d ":" -f2)

	# clean up and remove stuff from incoming file
	perl -e '$A=join("",<>); 
		$A=~s|BEGIN:VCALENDAR.*?BEGIN:VEVENT|BEGIN:VEVENT|sig; 
		$A=~s|\nUID.*?\n|\n|sig; 
		$A=~s|\nEND:VCALENDAR.*?\n|\n|sig; 
		$A=~s|\nCATEGORIES:.*?\n|\n|sig; 
		$A=~s|\nEND:VEVENT.*?\n|\n|sig; 
		$A=~s|X-OWASync-XML:.*?\n|\n|sig; 
		print "$A\n";' "$FILE" > "$FILE.tmp"

	mv "$FILE.tmp" "$FILE"

	# now tack on our CATEGORIES line so that we can identify this
	# record later...
	echo "CATEGORIES:WorkXChange" >> "$FILE"
	echo "UID:$MD5UID" >> "$FILE"
	echo "END:VEVENT" >> "$FILE"

}

function getKorgKeyValues
{
	
	KORGFILE="${WORKFILE}"
	FILE="$1"

	XGUID=$(grep "^UID:" "$FILE" | tail -1 | cut -d ":" -f2)

	# first, find and get the key values from our korganizer file
	perl -e '
$FNAME="$ARGV[0]";
$XGUID="$ARGV[1]";
open( FILE, "< $FNAME" ) or die "Cannot open $FNAME : $!";

while( <FILE> ) {
  chomp($_);

  # if we are at the beginning of an event, start over
  if ($_=~/^BEGIN:VEVENT/) {
    $VEVENT="";
    $PILOTID="";
    $UID="";
  }
 
  # check for the key values we will use to know if this is the right
  # calendar event...
  if ($_=~/^UID:/)  {   
    $UID="$_" ; 
    #print "found UID: [$_]\n";
  }
 
  # now check for the key values we need to put into the exchange file
  if ($_=~/^X\-PILOTID:/)  { $PILOTID="$_\n";  }
 
  # end of event. now inspect it. if this is the right VEVENT, print out the
  # key values that we need
  if ($_=~/^END:VEVENT/) {
    if ( $UID eq "UID:$XGUID" ) {
      # print out our key data for this VEVENT
      print "$PILOTID\n";
      exit;
    }
  }

  $VEVENT="$VEVENT$_\n";
 
}
close FILE;
	' "$KORGFILE" "$XGUID"  > /tmp/korgmatch.out

	TMPFILE="/tmp/korgmatch.tmp.ics"
	
	DATA=$(cat /tmp/korgmatch.out)

	# now strip out the ending tag and make sure everything we add to
	# it is also not there
	cat "$FILE" | egrep -v '^END:VEVENT|^X-PILOTSTAT' > "$TMPFILE"

 	# and put in what we got from above...
	echo "$DATA" >> "$TMPFILE"

	# if we had a pilot id before this sync, then show this record as
	# being modified so that it always gets pushed back into kpilot as
	# a modified record
	grep "X-PILOTID" "$TMPFILE" >/dev/null 2>&1
	rc=$?
	if [ $rc -eq 0 ]
	then
		echo "X-PILOTSTAT:1" >> "$TMPFILE"
	fi

	# make sure we have a valid beginning before we give it an
	# ending...
	grep "BEGIN:VEVENT" "$TMPFILE" >/dev/null 2>&1
	rc=$?
	if [ $rc -eq 0 ]
	then
		# now tack on the ending tag...
		echo "END:VEVENT" >> "$TMPFILE"
	fi

	echo "" >> "$TMPFILE"

	cp "$TMPFILE" "$FILE"

}

function cleanupKorgFile
{
	
	FILE="${WORKFILE}"

	# how many VEVENTS were there?
	BEGIN=$(grep "BEGIN:VEVENT" "${FILE}" | wc -l)

	# first, delete all VEVENTs that have my tag in it...
	perl -e '
$VEVENT="";
$IN=0;
while(<>) {
  # if we are at the beginning of an event, start over
  if ($_=~/^BEGIN:VEVENT/) {
    $VEVENT="";
    $IN=1;
  }

  $VEVENT="$VEVENT$_";

  # when do we print? well, if we get a END, then we see if we should
  # print. otherwise, if we are not IN the middle of a VEVENT, then we
  # print, else if we are in the middle of the VEVENT, then we buffer it to
  # check later
  if ($_=~/^END:VEVENT/ && $IN) {
    $IN=0;
    # end of event
    if ( $VEVENT=~/WorkXChange/ ) {
    } else {
      print $VEVENT;
    }
  } elsif (!$IN) {
    print $_;
  }

}
	' "$FILE" > "$FILE.tmp"

	mv "$FILE.tmp" "$FILE"

	END=$(grep "BEGIN:VEVENT" "${FILE}" | wc -l)

	if [ "$BEGIN" != "$END" ]
	then
		DIF=$(echo "$BEGIN - $END" | bc)
		echo "
Cleaning up old korganizer file.

Started with: [$BEGIN] events and you now have: [$END] events.
Removed: [$DIF] events.
		"
	fi
}

function mergeXtoK
{
	FILE="${WORKFILE}"

	# how many VEVENTS were there?
	BEGIN=$(grep "BEGIN:VEVENT" "${FILE}" | wc -l)

	# first, get rid of ending line
	sed -i -e 's,END:VCALENDAR,,' "$FILE"

	cat "$XEVENTS" >> "$FILE"

	echo "END:VCALENDAR" >> "$FILE"

	END=$(grep "BEGIN:VEVENT" "${FILE}" | wc -l)

	if [ "$BEGIN" != "$END" ]
	then
		DIF=$(echo "$END - $BEGIN" | bc)
		echo "
Merging exchange into korganizer.

Started with: [$BEGIN] events and you now have: [$END] events.
Added: [$DIF] events.
		"
	fi
}


# -- end of functions


echo "fetching calendar..."
cd ~/bin/ruby-exchange/
nice -n 20 ruby rexport-events.rb

rc=$?
if [ $rc -ne 0 ] || [ ! -s ruby-exchange-events.ics ] 
then
	echo "unable to fetch calendar. exiting."
	exit 1
fi

cp ruby-exchange-events.ics "$XEVENTS"
# clean up newlines
cat "$XEVENTS" | tr -d '\015' > "$XEVENTS.tmp"
mv "$XEVENTS.tmp" "$XEVENTS"
echo "done fetching calendar..."


cp "${MERGECAL}" "${WORKFILE}"
# clean up newlines
cat "$WORKFILE" | tr -d '\015' > "$WORKFILE.tmp"
mv "$WORKFILE.tmp" "$WORKFILE"

BEGINMD5=$(md5sum "${MERGECAL}" | awk '{print $1}')

# -- MAIN 

# now 1-way merge exchange into korganizer
# delete all old entries from korganizer's ics file
cleanupKorgFile
# copy everything from exchange to korganizer
mergeXtoK

perl -e '$A=join("",<>); 
	$A=~s|\n+\n\n|\n\n|sig; 
	print $A;' "$WORKFILE" > "$WORKFILE.tmp"
mv "$WORKFILE.tmp" "$WORKFILE"

# check the md5sum of the file now that we're done and ONLY overwrite it if
# it has not changed since we started
ENDMD5=$(md5sum "${MERGECAL}" | awk '{print $1}')

if [ "$BEGINMD5" = "$ENDMD5" ]
then
	echo "file same as when I started. overwriting it."
	cp "$WORKFILE" "$MERGECAL"
else
	echo "file has changed since I started. leaving it be."
fi

rm "$PIDFILE"

