#!/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"
export QT_PLUGIN_PATH="./plugins"

# run openmw-launcher 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=""

  # tell openmw script that it got started from launcher
  # run under gdb
  export DEBUG_START_FROM_LAUNCHER=1
  gdb -iex "set follow-fork-mode child" -iex "set detach-on-fork off" -iex "set follow-exec-mode same" --args ./openmw-launcher.x86_64 "$@"
  exit $?
fi

./openmw-launcher.x86_64 "$@"
