#!/bin/bash
# $Id: remozilla,v 1.2 2004/09/16 17:27:06 oliver Exp $
# try to reuse an existing mozilla
# Copyright (c) 2004 Oliver Beckstein <orbeckst@gmx.net>
# Made available under the GNU Public License.
#
me=$0
progname=$(basename ${me})

# or use htmlview
: ${MOZILLA:=/usr/local/bin/firefox}

usage="usage: ${progname} [options] [url ...]
Fire up MOZILLA=${MOZILLA} and connect to a running one
if available
-h,--help        this help
-s,--standalone  always start a new instance (allows to
                 select a different profile)
-t,--tabs        open tabs, not new windows
--delay TIME     wait TIME seconds before starting subsequent 
                 processes in standalone mode
"

use_remote=1;
open_tabs=0;
my_opts="";
delay=2;

while [ $# -gt 0 ]; do
    case $1 in
      --debug)     set -x;
                   my_opts="${my_opts} --debug";;
      -h|--help)   echo "${usage}"; exit 0;;
      -s|--standalone)
                   use_remote=0;;
      -t|--tabs)   open_tabs=1;
                   my_opts="${my_opts} --tabs";;
      -*)          echo "unknown option \`$1'."; exit 1;;
      *)           url_list="${url_list} $1";;
    esac;
    shift
done


# For mozilla commands see
# see http://www.mozilla.org/unix/remote.html

case $open_tabs in
  0)  mozillaOpenAs=new-window;;
  1)  mozillaOpenAs=new-tab;;
esac

if [ ${use_remote} = 1 ] && ${MOZILLA} -remote "ping()" 2>/dev/null; then
   # found a running one
   if [ -z "${url_list}" ]; then
      # just open a window
      ${MOZILLA} -remote "xfeDoCommand(openBrowser)"
   else
      # open one for every url
      for u in ${url_list}; do
          ${MOZILLA} -remote "openURL(${u},${mozillaOpenAs})";
      done
   fi
else
   # no mozilla running, or standalone requested, so just open one
   # place urls in ARGV for simple shift processing
   [ -n "${url_list}" ] && set -- ${url_list}
   ${MOZILLA} $1 &
   err=$?
   if [ "${err}" != "0" ]; then
      echo "Failed to start \`${MOZILLA} $1'."
      exit ${err}
   fi
   shift
   if [ $# -gt 0 ]; then
     # ... and try again recursively for the rest
     sleep ${delay}; # give user a fighting chance to select a profile
     exec ${me} ${my_opts} $*
   fi
fi
exit 0
   
