#!/bin/sh
address="$@"

# log for error checking
logfile=$HOME/Mail/openoffice-to-kmail.log


echo $@ >> $logfile

# find kmail in your path or specify
# kmail=/usr/bin/kmail
kmail=`which kmail`

# check to see if it is an attachment
if [ `echo $address | grep -q -c "attachment"` -eq 1 ] ; then
	
	stringtochange=$address
	
	# cut it at "attachment=" and return the stuff to the right of the "="
	kmailstep1=`echo $stringtochange | cut -d= -f2`
	
	# tell the logfile how it went
	echo kmailstep1 $kmailstep1 >> $logfile

	# remove the "file://" syntax leaving just the path to the attachment
	kmailstep2=`echo $kmailstep1 | sed  s#^\'file://## -`

	# get rid of any single quotes and a double left over from the above steps
	attachtokmail=`echo $kmailstep2 | sed s/\'\"$// -`
	
	# tell the log file about it
	echo Atachtokmail $attachtokmail >> $logfile
	
	# launch kmail and tell it about the attachment
	$kmail --attach $attachtokmail

	exit 0
fi

# check to see if it is a mailto link
if [ `echo $address | grep -q -c "mailto:"` -eq 1 ] ; then 
	
	# remove the mailto: syntax
	passtokmail=`echo $address | sed s/^mailto://`

	# tell the logfile the result
	echo passtokmail $passtokmail >> $logfile

	# if the URL has some fancy "subject=" query strings deal with it
	if [ `echo $passtokmail | grep -q -c "subject"` -eq 1 ] ; then
		# the address is to the left of the query string cut it at "?"
		emailaddress=`echo $passtokmail | cut -d? -f1`
		# the subject is to the right of the "=" 
		subject=`echo $passtokmail | cut -d= -f2`
		# if the subject has html special char encoding get ride of the %20 for spaces
		killspaces=`echo $subject | sed s/\%20/" "/g -`
		
		# launch kmail with the address in the to: field and the query string as the subject
		$kmail --composer $emailaddress --subject "$killspaces"
	else
		# if it doesn't have a subject query string just launch kmail with the address in the to field
		emailaddress=$passtokmail
		$kmail --composer $emailaddress
	fi
	
	exit 0

fi
