#!/bin/sh
#
# Title:  Mozilla Firefox Wrapper Script
# Author: Charles Dominguez (cfdoming)
# Based on: $Id: mozilla.athena.in,v 1.5.2.3 2004/01/02 20:05:21 ghudson Exp $
# Description:
#     Configures and runs Mozilla Firefox on Athena.
#
# Change Log:
#   2004-02-10  cfdoming  Initial version.
#   2004-02-17  ppham     Added Athena library path to LD_LIB_PATH.
#   2004-04-06  ppham     Added Xprint startup.
#   2004-04-27  cfdoming  Disabled Xprint startup (unneeded due to use of Autoconfig).
#   2004-07-02  cfdoming  Updated for new directory structure in locker.
#   2004-07-22  cfdoming  Changed handling of $MOZILLA_FIVE_HOME to try and fix Athena 9.3 bug.
#                         Added sanity checks to ensure all needed files are availible.
#   2004-07-23  cfdoming  Disabled Solaris patch checker.
#                         Updated for Firefox 0.9, new profile setup.


configdir='.mozilla/firefox'
oldConfigdir='.phoenix'
binary='firefox'
bindir=`athdir -p /mit/firebird -t bin`'/MozillaFirefox'
sharebin='/mit/firebird/arch/share/bin/MozillaFirefox'
profname='athena'
prefs="$sharebin/profiles/$profname/prefs.sh"
user="$sharebin/profiles/$profname/user.sh"
runver='current'
libpath='/usr/athena/lib'


zwrite ${USER} -m 'Mozilla Firefox now has its own locker on Athena-- the "firefox" locker.
To run Firefox, use the commands:

athena% add firefox
athena% firefox & 

The "firefox" locker is now the primary location for Firefox on Athena,
so please update your scripts and/or environment settings if needed.
' >/dev/null

echo '

Mozilla Firefox now has its own locker on Athena-- the "firefox" locker.
To run Firefox, use the commands:

athena% add firefox
athena% firefox & 

The "firefox" locker is now the primary location for Firefox on Athena,
so please update your scripts and/or environment settings if needed.

'



# Check script parameters
case "$1" in
--runver)
	# User is specifying the version to run.
	case "$2" in
	*[!a-z0-9A-Z._-]*|.|..)
		;;
	*)
		runver="$2"
		;;
	esac
	shift
	shift
	;;
--listver)
	# User only wants a list of availible versions
	curr=`ls -l $bindir | sed -n -e '/current -> / s/.* current -> //p'`
	echo "The current version of Mozilla Firefox for $ATHENA_SYS is:"
	echo "	${curr}"
	echo ''
	
	echo "The versions availible for $ATHENA_SYS are:"
	for dir in "$bindir"/[!.]*; do
		ver=`echo $dir | sed  -e 's#.*/##' -e '/current/d' `
		[ ${ver} ] && echo "	${ver}"
	done
	exit 0
esac

# Check that firefox binaries exist for the version specified
if [ ! -d "$bindir/$runver" ]; then
	echo "firefox.sh: The specified version of Mozilla Firefox could not be found."
	echo "To see a list of the availible versions, run the command:"
	echo "firefox --listver"
	exit 2
fi

# Set up the environment.
moz_libdir="$bindir/$runver"
if [ -z "$MOZILLA_FIVE_HOME" ]; then
	MOZILLA_FIVE_HOME=$moz_libdir
	export MOZILLA_FIVE_HOME
fi

# Sanity check to verify that the binaries are availible
if [ ! -r "$MOZILLA_FIVE_HOME/$binary"  -o  ! -r "$MOZILLA_FIVE_HOME/mozilla-xremote-client"  ]; then
	echo 'firefox.sh: Program binaries were not found.'
	echo "in: $MOZILLA_FIVE_HOME"
	echo 'Please email firebird@mit.edu to report this error.'
	exit 3
fi

# Disable the Solaris Patch Checker
MOZILLA_SOLARIS_PATCHCHECKER='disable_patchchecker'
export MOZILLA_SOLARIS_PATCHCHECKER


# mozilla-xremote-client sends a command to a running mozilla using
# X properties.  Its possible return codes are:
#   0  success
#   1  failed to connect to the X server
#   2  no running window found
#   3  failed to send command
#   4  usage error
moz_remote=$MOZILLA_FIVE_HOME/mozilla-xremote-client

# The following lockers need to be attached to run plugins and helper
# applications.
lockers="infoagents acro"

# Set up mozilla's runtime library path.
moz_lib_path=$MOZILLA_FIVE_HOME:$MOZILLA_FIVE_HOME/plugins:$libpath

case `uname` in
SunOS)
  # On Solaris, use the X server's shared memory transport for better
  # performance.
  if [ -z "$XSUNTRANSPORT" ]; then
    XSUNTRANSPORT=shmem
    XSUNSMESIZE=512
    export XSUNTRANSPORT XSUNSMESIZE
  fi
  # Ensure that we use the Sun gtk libraries.
  moz_lib_path=$moz_lib_path:/usr/sfw/lib
  java_plugin_dir=/usr/j2se/jre/plugin/sparc/ns610
  ;;
Linux)
  # Set LD_ASSUME_KERNEL to avoid a java crash upon exit.
  LD_ASSUME_KERNEL=2.4.1
  export LD_ASSUME_KERNEL
  java_plugin_dir=/usr/java/j2re1.4.2_04/plugin/i386/ns610-gcc32
  ;;
esac

LD_LIBRARY_PATH=$moz_lib_path${LD_LIBRARY_PATH:+":$LD_LIBRARY_PATH"}
export LD_LIBRARY_PATH

# Set the plugin path.  We allow the user to skip loading our
# standard plugins via the MOZ_PLUGIN_PATH_OVERRIDE variable.
if [ "${MOZ_PLUGIN_PATH_OVERRIDE+set}" = set ]; then
  MOZ_PLUGIN_PATH="$MOZ_PLUGIN_PATH_OVERRIDE"
else
  # Append our plugin path to the user's setting (if any).
  # The Java plugin is in the locally-installed JRE package, and its
  # directory is set above; others (besides the default "null" plugin)
  # live in infoagents.
  plugin_path=$java_plugin_dir:/mit/infoagents/arch/@sys/lib/mozilla/plugins
  MOZ_PLUGIN_PATH=${MOZ_PLUGIN_PATH:+"$MOZ_PLUGIN_PATH:"}$plugin_path
fi
export MOZ_PLUGIN_PATH

# Prompt the user on how to deal with an existing lock file when no
# running Mozilla window can be found, and take action accordingly.
# Parameter 1 is the existing profile lock file path.
# If the function returns, the lock file may have been removed per the
# user's choice, and the caller should continue.  Or, this process may
# exit, if the user so chooses.
dispose_lock () {
  lock=$1
  # Extract the IP address and PID from the contents of the symlink.
  eval `ls -l $lock | awk '{
    if (split($NF, a, ":") == 2)
      printf("lock_ip=%s ; lock_pid=%s\n", a[1], a[2]); }'`

  # If we cannot recognize the link contents, just continue.
  if [ -z "$lock_ip" ]; then
    return 0
  fi

  # See if the lock holder is on this machine by comparing IP addresses.
  my_host=`hostname`
  if [ "$lock_ip" = "`host $my_host | awk '{ print $NF; }'`" ]; then
    # Lock is held on this machine. See if the process is running.
    if kill -0 $lock_pid 2>/dev/null ; then
      # Lock is held by a running process.
      :
    else
      # Process is no longer running.  Nuke the lock and continue.
      rm -f $lock
      return 0
    fi
    lock_host="this machine"
  else
    # Lock is held on another machine.
    # Get the host name of the lock holder.
    lock_host=`host $lock_ip | \
        sed -n -e 's/^.*domain name pointer \(.*\)$/\1/p' | \
        sed -e 's/\.*$//' | tr '[A-Z]' '[a-z]'`
    if [ -z "$lock_host" ]; then
      lock_host=$lock_ip
    fi
  fi

  dialog_text="
  Your Mozilla Firefox profile directory contains a lock file, but no existing  
  Mozilla window can be detected.  The lock is owned by process $lock_pid  
  on $lock_host.  

  Note that running multiple instances of Mozilla Firefox will likely corrupt  
  your profile.  But, if you know for certain that this lock file is  
  stale, i.e. that you are not running Mozilla Firefox on $lock_host,  
  you may choose to delete the lock file and continue.  

  Otherwise, you may choose to continue with the lock file in place, in  
  which case Mozilla Firefox will display its Profile Manager, allowing you to  
  select or create a different profile (Mozilla Firefox will not permit you to  
  use a profile which it believes to be in use).  

  Or, you can simply exit, leaving the lock file in place.  
"

  tag=`gdialog --title "Mozilla Firefox profile locked" --radiolist "$dialog_text" \
         60 60 3 \
         Exit,     "leaving lock file in place"           on  \
         Continue, "and invoke Mozilla Firefox's Profile Manager" off \
         Delete    "lock file and proceed"                off 2>&1`

  case "$tag" in
  *Continue*)
    ;;
  *Delete*)
    rm -f $lock
    ;;
  *)
    exit 1
    ;;
  esac
}

# Give a warning if we're running on a dialup machine.
if [ -x /etc/athena/dialuptype ]; then
  cat << \EOF

*** PLEASE DO NOT RUN MOZILLA FIREBIRD ON THE DIALUPS! ***

Mozilla Firefox is a very large and resource-intensive program, and it is
not appropriate to run it on a dialup machine.

Please run Mozilla Firefox on your local machine rather than on a dialup.

Thank you.

EOF
fi

# Attach needed lockers.
for locker in $lockers ; do
  /bin/athena/attach -h -n -q $locker
done

# Add fonts for MathML.
infoagents_bindir=`athdir /mit/infoagents`
if [ -x $infoagents_bindir/add-mathml-fonts ]; then
  $infoagents_bindir/add-mathml-fonts
fi


# Generate the default config for the user if necessary.
if [ ! -d "$HOME/$configdir" -a ! -d "$HOME/$oldConfigdir" ]; then

	$MOZILLA_FIVE_HOME/$binary -CreateProfile $profname 2>/dev/null

	# Sanity check to make sure the profile was actually created
	if [ ! -d $HOME/$configdir/$profname.??? ]; then
		echo 'firefox.sh: Failed to create initial profile.'
		echo 'Please email firebird@mit.edu to report this error.'
		exit 4
	fi

	profdir=`ls -d $HOME/$configdir/$profname.???`
	
	cp -rf $sharebin/profiles/$profname/profroot/* "$profdir/"
	
	$prefs >> "$profdir/prefs.js"
	$user >> "$profdir/user.js"
	
fi



# Try and connect to an already running Firefox process.
#	command sent depends on arguments.
case "$1" in
-P|-*Profile*|-help|-h)
	# If the user specified a profile to use, is otherwise manipulating
	# profiles, or is just looking for help, skip the check for a running
	# Mozilla, and invoke the program now.
	exec $MOZILLA_FIVE_HOME/$binary "$@" 2> /dev/null
	exit 0
	;;
	
-*)
	# No URL argument given.
	$moz_remote "openURL(about:blank, new-window)" 2>/dev/null && exit 0
	;;
  
*:/*/|/*/)
	# Looks like a URL or absolute path.
	$moz_remote "openURL($1, new-window)" 2>/dev/null && exit 0
	;;
	
*:/*|/*)
	# BUGFIX:
	# Looks like a URL or absolute path without a trailing slash.
	# add the slash to fix a bug in xremote
	$moz_remote "openURL($1/, new-window)" 2>/dev/null && exit 0
	;;
	
*)
	# Handle a relative path.
	if [ -r "$1" ]; then
		uri="`pwd`/$1"
		$moz_remote "openURL($uri, new-window)" 2>/dev/null && exit 0
	else
		$moz_remote "openURL(about:blank, new-window)" 2>/dev/null && exit 0
	fi
	;;
esac



# We're still here, so Firefox is not running.
# Check for a (possibly stale) lock file in the default profile directory.
skip_lock_check=false
if [ -d $HOME/$configdir/$profname ]; then
	profdir=$HOME/$configdir/$profname
else
	profdir=$HOME/$configdir/default
fi

if [ -d "$profdir" ]; then
	for lock in $profdir/????????.slt/lock ; do
		if [ -h $lock ]; then
			# The profile is locked.  Ask the user how to deal with it.
			dispose_lock $lock
			break
		fi
	done
fi

# Run the Standard binary
exec $MOZILLA_FIVE_HOME/$binary "$@" 2>/dev/null

