#!/bin/sh
export MALLOC_CHECK_=0
# If you don't have readlink, fill in the path to hxplay.bin here.
HELIX_LIBS=/usr/share/RealPlayer ; 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

# REALPLAYSYMLINK and REALPLAYSCRIPT are only used to derive REALPLAYDIR

if [ ! -d "$HELIX_LIBS" ]; then
    REALPLAYSCRIPT=""
    
    if [ -h "$0" ]; then
        REALPLAYSYMLINK=`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"
            REALPLAYSCRIPT=`$READLINK $REALPLAYSYMLINK`
        elif [ -x "$PERL" ] ; then
            # echo "Using perl"
            REALPLAYSCRIPT=`$PERL -e 'print readlink($ARGV[0])' -- $REALPLAYSYMLINK`            
        elif [ -x "$PYTHON" ] ; then
            # echo "Using python"
            REALPLAYSCRIPT=`echo 'import os; print os.readlink("/usr/local/bin/hxplay")' | $PYTHON -`
        else
            # echo "Using ls (directory name cannot contain spaces)"
            REALPLAYSCRIPT=`ls -l $REALPLAYSYMLINK | sed -e 's/.* //'`
        fi
    else
        REALPLAYSCRIPT=`which $0`
    fi

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

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

    # setup environment
    # find our common, plugin and codec dlls
    HELIX_LIBS=$REALPLAYDIR
    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
REALPLAYBIN=$HELIX_LIBS/realplay.bin
if [ -n "$DEBUG" -a -x "$CATCHSEGV" ]; then
    $CATCHSEGV artsdsp $REALPLAYBIN ${1+"$@"}
else
    while /bin/true; do
        # Restart the player if exit code is 10
        $REALPLAYBIN "$@"
        if [ $? -ne 10 ]; then
           break
        fi
    done
fi
