#!/bin/sh

readlink() {
	path=$1

	if [ -L "$path" ]
	then
		ls -l "$path" | sed 's/^.*-> //'
	else
		return 1
	fi
}

SCRIPT="$0"
COUNT=0
while [ -L "${SCRIPT}" ]
do
	SCRIPT=$(readlink ${SCRIPT})
	COUNT=$(expr ${COUNT} + 1)
	if [ ${COUNT} -gt 100 ]
	then
		echo "Too many symbolic links"
		exit 1
	fi
done
GAMEDIR=$(dirname "${SCRIPT}")

cd $GAMEDIR

export LD_LIBRARY_PATH="./lib"

# run esmtool in debugger if DEBUG env var is set
if [ -n "$DEBUG" ]
then
  which gdb >/dev/null 2>/dev/null
  if [ "$?" -ne 0 ]
  then
    echo "Could not find gdb"
    exit 1
  fi
  # Make sure gdb does not try to download debuginfo files
  # (dont want to fill up disk space)
  export DEBUGINFOD_URLS=""
  gdb --args ./esmtool.x86_64 "$@"
  exit $?
fi

./esmtool.x86_64 "$@"
