#!/bin/sh

# If you don't have readlink, fill in the path to hxplay.bin here.
# HELIX_LIBS="/usr/local/HelixPlayer" ; export HELIX_LIBS

# To install this script, create a symlink to it from somewhere in your
# path.  Do *not* move the script out of the HelixPlayer directory, since
# it relies on the true location of hxplay to derive the location of the
# HelixPlayer directory

# HXPLAYSYMLINK and HXPLAYSCRIPT are only used to derive HXPLAYDIR

if [ ! -d "$HELIX_LIBS" ]; then
    HXPLAYSCRIPT=""
    
    if [ -h "$0" ]; then
        HXPLAYSYMLINK=`which $0`

        # Search for something we can use as readlink
        READLINK=`which readlink` 2> /dev/null;
        PERL=`which perl` 2> /dev/null;
        PYTHON=`which python` 2> /dev/null;
        if [ -x "$READLINK" ] ; then
            # echo "Using readlink"
            HXPLAYSCRIPT=`$READLINK $HXPLAYSYMLINK`
        elif [ -x "$PERL" ] ; then
            # echo "Using perl"
            HXPLAYSCRIPT=`$PERL -e 'print readlink($ARGV[0])' -- $HXPLAYSYMLINK`            
        elif [ -x "$PYTHON" ] ; then
            # echo "Using python"
            HXPLAYSCRIPT=`echo 'import os; print os.readlink("/usr/local/bin/hxplay")' | $PYTHON -`
        else
            # echo "Using ls (directory name cannot contain spaces)"
            HXPLAYSCRIPT=`ls -l $HXPLAYSYMLINK | sed -e 's/.* //'`
        fi
    else
        HXPLAYSCRIPT=`which $0`
    fi

    if [ ! -x "$HXPLAYSCRIPT" ] ; then
        echo "Cannot find the HelixPlayer directory."
        echo "Please set the path in the hxplay script."
        exit
    fi

    # if HXPLAYDIR detection doesn't work, hardcode the directory here
    HXPLAYDIR=`dirname $HXPLAYSCRIPT`

    # setup environment
    # find our common, plugin and codec dlls
    HELIX_LIBS=$HXPLAYDIR
    export HELIX_LIBS
fi

# See if LD_PRELOAD contains any of the sound server libs. If so, remove them.
LD_PRELOAD=`echo $LD_PRELOAD | sed -e 's/\([^:]*libesd[^:]*\|[^:]*libarts[^:]*\):\?//g'`
export LD_PRELOAD

if [ -n "$LD_PRELOAD" ]; then
    echo "Warning: LD_PRELOAD=\"$LD_PRELOAD\""
fi
    
# execute binary (and pass args), optionally running via catchsegv
CATCHSEGV=`which catchsegv`
HXPLAYBIN=$HELIX_LIBS/hxplay.bin
if [ -n "$DEBUG" -a -x "$CATCHSEGV" ]; then
    $CATCHSEGV $HXPLAYBIN ${1+"$@"}
else
    while /bin/true; do
        # Restart the player if exit code is 10
        $HXPLAYBIN "$@"
        if [ $? -ne 10 ]; then
           break
        fi
    done
fi
