#!/bin/sh
#
# Copyright (c) 2008 Owen Williams
# You may use and distribute this software under the terms of the
# GNU General Public License, version 2 or later
#


# run-moz code from Conduit (thanks!)

## Work around https://bugs.launchpad.net/ubuntu/+source/firefox/+bug/26436
## Note: This bug is also present in Mandriva and Fedora, for this reason, 
## We will use run-mozilla in all cases
##
## Run mozilla takes care of settin up the appropriate environment variables
## to run a program using mozilla libs

if [ "$1"x = "--no-launcher"x ] ; then
	USE_LAUNCHER=0
	shift
else
	USE_LAUNCHER=1
fi


HILDON=0
RUNMOZ_DIR=""
if [ "$PYTHON"x = "x" ] ; then
	PYTHON="/usr/bin/env python"
fi

if [ -f "/usr/lib/libgtkembedmoz.so.0" -a -d "/usr/lib/microb-engine" ]; then
	HILDON=1
	echo "Launching Hildon version"
	#export MOZILLA_FIVE_HOME="/usr/lib/microb-engine"
	#export LD_LIBRARY_PATH="/usr/lib/microb-engine"
else
	if [ "$WITH_MOZ_DIR"x = "x" ] ; then
		for d in `ls -d  /usr/lib*/firefox* /usr/lib*/mozilla-firefox* /usr/lib*/xulrunner* 2> /dev/null | grep -v addons | grep -v devel | sort -r`
		do
			if [ -x $d/run-mozilla.sh ]; then
			    echo INFO: FOUND FIREFOX LIBS AT $d
			    WITH_MOZ_DIR="$d"
			    break
			fi
		done
	fi
fi
	
rundir=`dirname $0`
cd $rundir
	
if [ -f "./penguintv/penguintv.py" ] ; then
	ptv_home="./penguintv"
elif [ -f "../penguintv/penguintv.py" ] ; then
	cd ..
	ptv_home="./penguintv"
elif [ -d "/usr/lib/python2.5/site-packages/penguintv" ] ; then
	ptv_home="/usr/lib/python2.5/site-packages/penguintv"
else
	ptv_home=`$PYTHON -c "import os, sys; 
if os.environ.has_key('PENGUINTV_LIB'): 
    print os.environ['PENGUINTV_LIB'];  
    sys.exit(0); 
for d in [\"$rundir\"] + sys.path:
    if len(d) > 0:
        if d[0] == '.':
            d = os.path.join(os.getcwd(), d);
        sd = os.path.join(d, 'penguintv'); 
        if os.path.isdir(sd):
            print sd; 
            sys.exit(0); 
h, t = os.path.split(os.path.split(os.path.abspath(sys.argv[0]))[0]); 
if t == 'bin': 
    libdir = os.path.join(h, 'lib'); 
    fp = os.path.join(libdir, 'penguintv'); 
    if os.path.isdir(fp): 
        print libdir; 
        sys.exit(0); 
sys.exit(1)"`
	if [ $? -gt 0 ] ; then
		echo "Error finding PenguinTV library home.  Please export PENGUINTV_LIB"
		exit 1
	fi
fi

echo "Running ptv in $ptv_home"
export PTV_PREFIX=$rundir

if [ $HILDON -eq 1 ] ; then	
	PYTHONPATH="$ptv_home"
	cd $ptv_home
	if [ $USE_LAUNCHER -eq 1 ] ; then
		run-standalone.sh /usr/bin/python ./penguintv.py $*
	else
		run-standalone.sh /usr/bin/python2.5 ./penguintv.py $*
	fi
else
	PYTHONPATH="$ptv_home"
	cd $ptv_home
	if [ "$WITH_MOZ_DIR"x = "x" ] ; then
		echo "WARNING: COULD NOT FIND FIREFOX LIBRARIES"
		echo "WARNING: PENGUINTV MAY CRASH UNEXPECTEDLY"
		echo "Please export WITH_MOZ_DIR with the location of run-mozilla.sh to correct this issue"
		$PYTHON ./penguintv.py $*
	else
		$WITH_MOZ_DIR/run-mozilla.sh $PYTHON ./penguintv.py $*
	fi
fi
