#!/bin/bash

# Original binary
BINARY_ORG="$0"
if [ ! ${BINARY_ORG:0:1} = "/" ]
then
   BINARY_ORG=`pwd`/$BINARY_ORG
fi

# Binary
BINARY=$BINARY_ORG
while [ `readlink $BINARY` ]
do
    BINARY=`readlink $BINARY`
done

# Binary dir
if [ ${BINARY:0:1} = "/" ]
then
    BINARY_DIR=`dirname $BINARY`
else
    BINARY_DIR=`dirname $BINARY_ORG`/`dirname $BINARY`
    BINARY_DIR=`cd $BINARY_DIR ; pwd` 
fi

# Take a look to the current directory
if [ -d "$BINARY_DIR/xulrunner" ]
then
    if [ -e "$BINARY_DIR/xulrunner/xulrunner-bin" ]
    then
	XULRUNNER="$BINARY_DIR/xulrunner/xulrunner-bin"
    elif [ -e "$BINARY_DIR/xulrunner/xulrunner" ]
    then
	XULRUNNER="$BINARY_DIR/xulrunner/xulrunner"
    fi
fi

# Try to update $LD_LIBRARY_PATH
for DIR in `find $BINARY_DIR -type d -name xulrunner`; do
    export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$DIR;
done

# Add /usr/local/lib to $LD_LIBRARY_PATH as it seems no always be the case per default
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib

# If no local xulrunner binary try different name on the system
if [ ! "$XULRUNNER" ]
then
  XULRUNNER_NAMES="xulrunner-1.9.2 xulrunner-10.0 xulrunner-9.0 \
                   xulrunner-8.0 xulrunner-7.0 xulrunner-6.0 xulrunner-5.0 xulrunner-4.0 \
                   xulrunner-3.0 xulrunner-2.0 xulrunner-1.9.1 xulrunner";
  for NAME in $XULRUNNER_NAMES
  do
    XULRUNNER=`which $NAME`
    if [ "$XULRUNNER" ]
    then
	break;
    fi
  done;
fi

# If no result print a message
if [ ! "$XULRUNNER" ] || [ ! -f "$XULRUNNER" ] || [ ! -x "$XULRUNNER" ] || [ ! -r "$XULRUNNER" ]
then
    echo "'xulrunner' is not installed, you have to install it to use Kiwix."
    exit;
fi

# Set the custom plugins directory
export MOZ_PLUGIN_PATH=/usr/lib

# Otherwise, launch Kiwix
if [ -f $BINARY_DIR/../lib/kiwix/application.ini ]
then
    $XULRUNNER $BINARY_DIR/../lib/kiwix/application.ini "$@"
else
    $XULRUNNER $BINARY_DIR/application.ini "$@"
fi
