#!/bin/sh
#
# $NetBSD: ns-open,v 1.18 2008/01/01 16:45:35 abs Exp $
#
# Simple script to open a URL in Netscape, starting a new process if necessary
# If a netscape process is not running it will look for a valid netscape
# binary in the colon separated NETSCAPE_PREFERRED list, which can be
# overridden by the user in the environment.

if [ -z "$NETSCAPE_PREFERRED" ]; then
    NETSCAPE_PREFERRED=firefox:seamonkey:netscape7:mozilla:communicator:navigator:mozilla-netbsd:mozilla-linux:mozilla-solaris:firefox-netbsd:firefox-gtk2-linux:firefox-linux:firefox-solaris
fi

# Locate appropriate netscape binary and set NETSCAPE_BIN
# If we cannot locate, do not fail with an error here as we may still be
# able to use ns-remote to talk to an existing netscape process.
#
oldIFS="$IFS"
IFS="${IFS}:"
for prog in $NETSCAPE_PREFERRED ; do
    case $prog in
	/*) if [ -x $prog ]; then
		NETSCAPE_BIN=$prog
		break 2
	    fi
	    ;;
	*)  for dir in $PATH;do
		if [ -x $dir/$prog ];then
		    NETSCAPE_BIN=$dir/$prog
		    break 2
		fi
	    done
	    ;;
    esac
done
IFS="$oldIFS"

escape()
    {
    str=$1
    echo "$str" | sed -e 's/ /%20/g' -e 's/"/%22/g' -e 's/,/%2c/g' -e 's/\`/%60/g'
    }

# Check if there are any '-' options which would not be understood by ns-remote
# Slightly involved to avoid changing $@ in case we need it for real netscape
#
for a
do
    if [ "$SKIP_ARG" = 1 ];then
	NS_REMOTE_ARGS="$NS_REMOTE_ARGS $a"
	SKIP_ARG=0
	continue
    fi
    case $a in
	-display | -id)
	    SKIP_ARG=1
	    ;;
	-remote)
	    REMOTE_SPECIFIED=1
	    SKIP_ARG=1
	    ;;
	-raise | -noraise)
	    RAISE=
	    ;;
	-* ) # Unrecognised option
	    START_NEW_NETSCAPE=1
	    ;;
	*)
	    URL=`escape "$a"`
	    break;
	    ;;
    esac
    NS_REMOTE_ARGS="$NS_REMOTE_ARGS $a"
done

# If we recognised all the options, try ns-remote
#
if [ -z "$START_NEW_NETSCAPE" ];then
    NS_REMOTE_ARGS="$NS_REMOTE_ARGS $RAISE"
    if [ -z "$REMOTE_SPECIFIED" ];then
	if [ -z "$URL" ];then
	    URL=about:blank
	fi
	NS_REMOTE_ARGS="$NS_REMOTE_ARGS -remote openURL(${URL})"
    fi
    if ns-remote -noraise 2>/dev/null; then
        if ns-remote $NS_REMOTE_ARGS ; then
            exit 0
        fi
    else
        echo "Netscape not running. Spawning $NETSCAPE_BIN in background." >&2
    fi
fi

if [ -z "$NETSCAPE_BIN" ];then
    echo "Unable to locate netscape binary for '$NETSCAPE_PREFERRED'"
    exit 1
fi
case $1 in
    -*)
	$NETSCAPE_BIN "$@"
	;;
    *)
	# Since using ns-remote will return, we start netscape in the
	# background to give consistent behaviour.
	$NETSCAPE_BIN "$@" &
	;;
esac
exit 0
