#!/bin/sh

# check if we got started from launcher also run under gdb
# then we are already in a gdb session and need to directly
# start openmw-navmeshtool
if [ -n "$DEBUG" ] && [ -n "$DEBUG_START_FROM_LAUNCHER" ]
then
  exec ./openmw-navmeshtool.x86_64 "$@"
fi

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 openmw-navmeshtool 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 ./openmw-navmeshtool.x86_64 "$@"
  exit $?
fi

./openmw-navmeshtool.x86_64 "$@"
