#!/bin/sh
#
# firefox-remote - Wrapper script for firefox web browser and thunderbird
# mail client
#
# to enable mailto: in firefox the easiest way is to install the MozEx
# navigation extension and use "/usr/X11R6/bin/thunderbird-remote %r"
# (without quotes) as the Mailer command.
#

X11BASE="/usr/local"
USE_UTF8_LOCALE="no"

FIREFOX_CMD="${X11BASE}/bin/firefox"
THUNDERBIRD_CMD="${X11BASE}/bin/thunderbird"
TRUE="/usr/bin/true"
SED="/usr/bin/sed"
BASENAME="/usr/bin/basename"
ECHO="/bin/echo"

FIREFOX_VERSION=`${FIREFOX_CMD} -V | ${SED} -E 's|,.*||;s|[^0-9\.]||g'`
MOZILLA_XREMOTE="${X11BASE}/lib/firefox/lib/firefox-${FIREFOX_VERSION}/mozilla-xremote-client"

SCRIPTNAME=`${BASENAME} $0`

# quick and dirty hack - firefox/thunderbird has problem with unicode filenames
# and "umlaute" eg.: 

if [ "${USE_UTF8_LOCALE}" = "yes" ]; then
	UTF8_LANG="${LANG%ISO*}UTF-8"
	if [ -d /usr/share/locale/$UTF8_LANG ]; then
	       export LANG=${UTF8_LANG}
	fi 
fi

remote_fox()
{
	if [ "$1x" = "x" ]; then
        	URL="about:blank"
	else    
        	URL=$1
	fi

	FIREFOX_REMOTE="openURL(${URL},new-tab)"

	if [ -f ${MOZILLA_XREMOTE} ]; then
		FIREFOX_PING=${TRUE}
		FIREFOX_RCMD="${MOZILLA_XREMOTE} -a firefox"
	else
		FIREFOX_PING="${FIREFOX_CMD} -remote ping()"
		FIREFOX_RCMD="${FIREFOX_CMD} -remote"
	fi

	${FIREFOX_PING} 	 		&& 
	${FIREFOX_RCMD} ${FIREFOX_REMOTE} 	&& exit 0 

	${FIREFOX_CMD} ${URL}
}


remote_bird()
{

	if [ "$1x" = "x" ]; then
		MAILTO=""
	else    
        	MAILTO=`${ECHO} $@ | ${SED} 's| |%20|g;s|mailto:||'`
	fi

	THUNDERBIRD_REMOTE="mailto(${MAILTO})"

# thunderbird 0.7 doesn't support mozilla-xremote-client
#	if [ -f ${MOZILLA_XREMOTE} ]; then
#		THUNDERBIRD_PING=${TRUE}
#		THUNDERBIRD_RCMD="${MOZILLA_XREMOTE} -a thunderbird"
#	else
		THUNDERBIRD_PING="${THUNDERBIRD_CMD} -remote ping()"
		THUNDERBIRD_RCMD="${THUNDERBIRD_CMD} -remote"
#	fi

	${THUNDERBIRD_PING} 	 			&& 
	${THUNDERBIRD_RCMD} ${THUNDERBIRD_REMOTE} 	&& exit 0 

	if [ "$1x" = "x" ]; then
		${THUNDERBIRD_CMD}
	else
		${THUNDERBIRD_CMD} -mail mailto:${MAILTO}
	fi
}


if [ "${SCRIPTNAME}" = "thunderbird-remote" ] ; then
	remote_bird $1
else
	remote_fox $1
fi
