#!/bin/sh



# Function to find the real directory a program resides in.
# Feb. 17, 2000 - Sam Lantinga, Loki Entertainment Software
FindPath()
{
    fullpath="`echo $0 | grep /`"
    if [ "$fullpath" = "" ]; then
        oIFS="$IFS"
        IFS=:
        for path in $PATH
        do if [ -x "$path/$0" ]; then
               if [ "$path" = "" ]; then
                   path="."
               fi
               fullpath="$path/$0"
               break
           fi
        done
        IFS="$oIFS"
    fi
    if [ "$fullpath" = "" ]; then
        fullpath="$0"
    fi
 
    # Is the sed/ls magic portable?
    if [ -L "$fullpath" ]; then
        #fullpath="`ls -l "$fullpath" | awk '{print $01}'`"
        fullpath=`ls -l "$fullpath" |sed -e 's/.* -> //' |sed -e 's/\*//'`
    fi
    dirname $fullpath
}





# Setup variables

#get the dir where this script resides in
set -- $(FindPath)
path=$*
test=$1
#if [ "$fullpath" = "" ]; then
if [ "$test" = "." ]; then
	path=${PWD}
fi
prefix=${path}/..

echo "According to my calculations Ember should be installed in $prefix"

exec_prefix=${prefix}
bindir=${exec_prefix}/bin
datadir=${prefix}/share/ember
media_user_dir=${datadir}/media/user
etcdir=${prefix}/etc/ember

LD_LIBRARY=$prefix/lib/ember:$LD_LIBRARY
LD_LIBRARY_PATH=$prefix/lib/ember:$LD_LIBRARY_PATH
export LD_LIBRARY
export LD_LIBRARY_PATH


homedata=$HOME/.ember
case "$1" in
--home)
  shift
  homedata="$@"
  ;;
esac

media_dir="${homedata}/ember-media-0.5.0"


# Create dir if required 
if [ ! -d $homedata ] ; then
	echo "Creating $homedata to store all game data."
	mkdir -p $homedata
else
	#if an older version have been installed, move the ember.conf out of the way
	if [ ! -e $homedata/latest_version ]; then
		echo "Checking for old config files and moving them out of the way."
		if [ -e $homedata/ember.conf ]; then
			mv $homedata/ember.conf $homedata/ember.conf.old
		fi
		if [ -e $homedata/ogre.cfg ]; then
			mv $homedata/ogre.cfg $homedata/ogre.cfg.old
		fi
		if [ -e $homedata/plugins.cfg ]; then
			mv $homedata/plugins.cfg $homedata/plugins.cfg.old
		fi
	fi
fi

if [ ! -d $media_dir ] ; then
	echo "Copying dynamic data to user directory"
	cp -pR $media_user_dir $media_dir
fi

#Let's write the version number so that we can do some useful thing with it in the future. (Like remove old media dirs.)
echo 0.5.0 > $homedata/latest_version

# Execute real ember binary
echo "Starting Ember...."
#we have to do the LD_PRELOAD thing, because else at least I get an error: libnvidia-tls.so.1: cannot handle TLS data /ehj
[ ! -f $homedata/plugins.cfg ] && cp $etcdir/plugins.cfg $homedata/
[ ! -f $homedata/resources.cfg ] && cp $etcdir/resources.cfg $homedata/
+LD_PRELOAD=libGL.so.1 $bindir/ember.bin
