#!/bin/sh

TARGET=/usr/share/firefox_0.9.1/firefox
#REMOTE="/usr/lib/mozilla/mozilla-xremote-client -a firefox"
REMOTE="/usr/lib/mozilla/mozilla-xremote-client"

if [ "$1" == "-remote" ]; then
    # calling program is smart enough to do it...
    exec $TARGET $*

else
#    `$REMOTE "ping ()"`
    `/usr/share/firefox_0.9.1/mozilla-xremote-client -a firefox "ping ()"`
    if [ $? = 0 ] ; then
	echo "Already running ($?)"
        # there is already one running

        if [ -z "$1" ]; then
	    exec $REMOTE "openURL("about:blank", new-window)"

        elif [ -f "$1" ]; then
            # okay, tedious work of trying to find the complete pathname
            # make two variables, trying to separate the path from file.
            file=`basename $1`
            path=${1%%${file}}
	    if [ ! -d "$path" ]; then
        	# try to fully expand the path
        	path=`pwd $path`
	    fi
            # okay, issue the command
	    exec $REMOTE "openFile(file://$path/$file, new-tab)"

        else
	    # "new-tab" feature for URLs is broken in current firefox
	    #exec $REMOTE "openURL($1, new-tab)"
	    # so what we do instead is always open a new window and then
	    # open the URL
	    $REMOTE "xfeDoCommand(openBrowser)"
	    exec $REMOTE "openURL($1)"

        fi
    else
        # no mozilla currently running
	echo "Nothing running ($?)"
        exec $TARGET $* &

    fi
fi
