#!/bin/sh

plumbfirefox()
{
	echo '
		tell application "Firefox"
		activate
		tell application "System Events"
		tell process "firefox"
		keystroke "t" using {command down}
		end tell
		end tell
		Get URL "'$1'"
		end tell
	' | osascript
}

plumbsafari()
{
	echo '
		tell application "Safari"
		activate
		tell application "System Events"
		tell process "safari"
		keystroke "t" using {command down}
		end tell
		end tell
		open location "'$1'"
		end tell
	' | osascript
}

plumbapple()
{
	case ${BROWSER:-none} in
	firefox)
		plumbfirefox "$@"
		;;
	safari)
		plumbsafari "$@"
		;;
	none)
		if [ -d /Applications/Firefox.app ]
		then
			plumbfirefox "$@"
		else
			plumbsafari "$@"
		fi
		;;
	esac
}

plumbunix()
{
	case "${BROWSER:=firefox}" in
	# Other browsers here
	# ...
	*opera*)
		$BROWSER -remote 'openURL('"$i"',new-page)'
		;;
	*firebird*)
		$BROWSER -remote 'openURL('"$i"',new-window)'
		;;
	*firefox*)
		$BROWSER -remote 'openURL('"$i"',new-tab)' ||
		$BROWSER "$i"
		;;
	*mozilla*)
		$BROWSER -remote 'openURL('"$i"',new-tab)' ||
		$BROWSER "$i"
		;;
	esac
}

plumb1()
{
	case `uname` in
	Darwin)
		plumbapple "$@"
		;;
	*)
		plumbunix "$@"
		;;
	esac
}


if [ $# = 0 ]
then
	plumb1 about:blank
else
	for i
	do
		if [ -f "$i" ]
		then
			p=`pwd`
			i=`echo $i | sed 's/ /%20/g'`
			i=`cleanname -d $p $i`
			i=file://$i
		else
			i=`echo $i | tr -d ' '`
		fi
		plumb1 $i
	done
fi

case $BROWSER in
*opera*)
	$BROWSER -remote 'raise()'
esac