#!/bin/sh

### Written by Dag Wieers <dag@wieers.com>
### Please send suggestions and fixes to me.

ulimit -c 0

MOZILLA_FIVE_HOME="/usr/lib/firefox"
MOZ_PROGRAM="$MOZILLA_FIVE_HOME/firefox"

LD_LIBRARY_PATH="$MOZILLA_FIVE_HOME:$MOZILLA_FIVE_HOME/plugins:$LD_LIBRARY_PATH"
MOZ_PLUGIN_PATH="$HOME/.mozilla/plugins:$MOZILLA_FIVE_HOME/plugins:/usr/lib/mozilla/plugins"
FONTCONFIG_PATH="/etc/fonts:$MOZILLA_FIVE_HOME/res/Xft"
export MOZILLA_FIVE_HOME LD_LIBRARY_PATH MOZ_PLUGIN_PATH FONTCONFIG_PATH

MOZARGS=""
MOZLOCALE="$(echo $LANG | sed 's|_\([^.]*\).*|-\1|g')"
if [ -f "$MOZILLA_FIVE_HOME/chrome/$MOZLOCALE.jar" ]; then
	MOZARGS="-UILocale $MOZLOCALE"
fi

$MOZ_PROGRAM -remote 'ping()' &>/dev/null
RUNNING=$?
if [ $? -eq 2 ]; then RUNNING=0; fi

CMD=0
while [ "$1" ]; do
	case "$1" in
#	  -mail|-email)
#		if [ $RUNNING -eq 0 -a $CMD -ne 1 ]; then
#			MOZARGS="-remote xfeDoCommand(openInbox) $MOZARGS"
#			CMD=1
#		fi;;
#	  -compose|-editor)
#		if [ $RUNNING -eq 0 -a $CMD -ne 1 ]; then
#			MOZARGS="-remote xfeDoCommand(composeMessage) $MOZARGS"
#			CMD=1
#		fi;;
	  -remote)
		if [ $CMD -ne 1 ]; then
			MOZARGS="-remote $2 $MOZARGS"
			CMD=1
		fi
		shift;;
	  -profile|-profile-manager)
		CMD=1
		;;
	  -*)
		MOZARGS="$MOZARGS $1"
		;;
	  *)
		if [ $CMD -ne 1 ]; then
			if [ -e "$PWD/$1" ]; then
				URL="file://$PWD/$1"
			elif [ -e "$1" ]; then
				URL="file://$1"
			else
				URL="$1"
			fi
			if [ $RUNNING -eq 0 ]; then
				MOZARGS="-remote openURL(\"$URL\",new-window) $MOZARGS"
			else
				MOZARGS="-remote openURL(\"$URL\") $MOZARGS"
			fi
			CMD=1
		else
			MOZARGS="$MOZARGS $1"
		fi;;
	esac
	shift
done

if [ $RUNNING -eq 0 -a $CMD -ne 1 ]; then
	exec $MOZ_PROGRAM -remote "xfeDoCommand(openBrowser)" $MOZARGS
else
	exec $MOZ_PROGRAM $MOZARGS &
fi;
