#!/bin/sh

# gnome-moz-remote: Remote controller of Mozilla, like gnome-moz-remote

usage () {
  echo "Usage: gnome-moz-remote [--newwin|-w] [--newtab|-t] [URL|file]"
}

check_cmd () {
  local FULLPATH

  if [ -x "$1" ]; then
    echo "$1"
  else
    FULLPATH=`which "$1" 2> /dev/null`
    if [ $? = 0 -a -x "$FULLPATH" ]; then
      echo "$FULLPATH"
    fi
  fi
}

GCONF_KEY="/desktop/gnome/applications/browser/exec"

NEWWIN=n
NEWTAB=n

URL=
for n in "$@"; do
  case "$n" in
    --newwin|-w)
      NEWWIN=y
      ;;
    --newtab|-t)
      NEWTAB=y
      ;;
    -*)
      usage
      ;;
    *:*)
      if [ -n "$URL" ]; then
	usage
      fi
      URL="$n"
      ;;
    /*)
      if [ -n "$URL" ]; then
	usage
      fi
      URL="file://$n"
      ;;
    *)
      if [ -n "$URL" ]; then
	usage
      fi
      URL="file://`pwd`/$n"
      ;;
  esac
done

if [ -z "$GNOME_MOZ_BROWSER" ]; then
  GNOME_MOZ_BROWSER=`gconftool-2 -g "$GCONF_KEY" 2> /dev/null`
fi

if [ -n "$GNOME_MOZ_BROWSER" ]; then
  GNOME_MOZ_BROWSER=`check_cmd "$GNOME_MOZ_BROWSER"`
fi

if [ -z "$GNOME_MOZ_BROWSER" ]; then
  for b in mozilla phoenix netscape; do
    GNOME_MOZ_BROWSER=`check_cmd "$b"`
    if [ -n "$GNOME_MOZ_BROWSER" ]; then
      break
    fi
  done
fi

if [ -z "$GNOME_MOZ_BROWSER" ]; then
  echo "No web browsers found. Try setting GNOME_MOZ_BROWSER."
  exit 1
fi

gconftool-2 -t string -s "$GCONF_KEY" "$GNOME_MOZ_BROWSER"

if ! $GNOME_MOZ_BROWSER -remote 'ping()' 2> /dev/null; then
  if [ -n "$URL" ]; then
    exec $GNOME_MOZ_BROWSER "$URL"
  else
    exec $GNOME_MOZ_BROWSER
  fi
elif [ "$NEWWIN" = "y" -a -z "$URL" ]; then
  exec $GNOME_MOZ_BROWSER -remote "xfeDoCommand(openBrowser)"
else
  RMTOPT=
  if [ "$NEWWIN" = "y" ]; then
    RMTOPT=",new-window"
  elif [ "$NEWTAB" = "y" ]; then
    RMTOPT=",new-tab"
  fi
  if [ -n "$URL$RMTOPT" ]; then
    exec $GNOME_MOZ_BROWSER -remote "openURL($URL$RMTOPT)"
  fi
fi
