#!/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" || (echo "Failed to enter game directory $GAMEDIR" && exit 1)

export LD_LIBRARY_PATH="./lib"

# run niftool 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 ./niftool.x86_64 "$@"
  exit $?
fi

./niftest.x86_64 "$@"
