#! /bin/bash
#
# if firefox is already running, send it a command
# if started without arguments, open a new window, else a new tab

# JMD: the original behavior was to ping firefox to see if there's another 
# window open. However, this fails if firefox was spawned by Thunderbird.
# In this case, ping does not work, but pgrep works. But there's one more
# catch: since Thunderbird already exports MOZILLA_FIVE_HOME and other
# variables, we have to use bash -login and call run_mozilla, otherwise
# firefox fails to find its previous windows.

CFG="/etc/custom/apps/firefox/config/userinstall"
if [ -x $CFG ]; then
 $CFG
fi

# Get the most recent version of firefox installed
DIR=`ls -1 -d /usr/lib/mozilla-firefox-* | sort | tail -n 1`
if [ -d $DIR ]; then
  FFDIR=$DIR
  FFNAME=mozilla-firefox
  FFBIN=mozilla-firefox-bin
  FFPROG=/usr/bin/$FFNAME
  FFPING=firefox
fi

# Custom firefox has precedence
DIR=/opt/firefox
if [ -d $DIR ]; then
  FFDIR=$DIR
  FFNAME=firefox
  FFBIN=firefox-bin
  FFPROG=$FFDIR/$FFNAME
  FFPING=firefox
fi

if [ ! -e $FFDIR/$FFBIN ]; then
  echo 
  echo "Firefox not detected!"
  echo
  echo
  echo "FFDIR=$DIR"
  echo "FFNAME=mozilla-firefox"
  echo "FFBIN=mozilla-firefox-bin"
  echo "FFPROG=/usr/bin/$FFNAME"
  echo "FFPING=firefox"
 exit
fi

debug() {
  echo > /dev/null  
  #gmessage $@;
}

restartme() {
  if [ -z $FFNAME ]; then
    gmessage "Firefox doesn't have a name!"
    exit
  fi
  pkill -u `id -un` "$FFNAME"
  sleep 3
  pkill -9 -u `id -un` "$FFNAME"
  
  if [ -z "$URL" ]; then
    debug "CRASHED! Restarting a new Firefox"
    $FFPROG &
  else
    debug "CRASHED! Restarting with URL"
    $FFPROG -url $@ &
  fi
}

URL=$1
if $FFPROG -a $FFPING -remote "ping()" 2> /dev/null ; then
    if [ -z "$URL" ]; then
        debug "Started (Ping), blank"
	$FFPROG -a $FFPING -remote "xfeDoCommand (openBrowser)" || \
	  $FFPROG -a $FFPING -remote "openURL(about:blank)"
    else
        debug "Started (Ping), with url"
	$FFPROG -a $FFPING -remote "openURL($1,new-tab)"
    fi
elif pgrep -u `id -un` "$FFNAME" > /dev/null ; then
    if [ -z "$URL" ]; then
        debug "Started (PS), blank"
        bash -login $FFDIR/run-mozilla.sh \
        $FFDIR/$FFBIN  -a $FFPING \
        -remote "xfeDoCommand (openBrowser)"  || restartme
    else
        debug "Started (PS), with url"
        bash -login $FFDIR/run-mozilla.sh \
        $FFDIR/$FFBIN  -a $FFPING \
        -remote "openURL($URL,new-window)" || restartme $URL
    fi
else
    if [ -z "$URL" ]; then
      debug "Not Started, no url"
      $FFPROG &
    else
      debug "Not Started, with url"
      $FFPROG -url $URL &
    fi
fi
