#!/bin/sh -eu

# Store away original args before they are overwritten
orig_args=$@

: ${bindir:="$( cd -P "$( dirname "$0" )" && pwd )"}
: ${prefix:="$( cd -P "$( dirname "$0" )/.." && pwd )"}

debugging=0

while [ $# -gt 0 ]; do
  case "$1" in
  --debug)
    debugging=1
    ;;
  --help)
    echo "--debug       - start in debugger (requires that 'gdb' is installed)"
    exec $bindir/ember.bin --help >&2
    exit 1
    ;;
  esac
  shift
done

# Rely on built-in paths for installed binaries.
# Note that because of an issue with how CEGUI 0.8.2 detects dynamic libraries we need to include the CEGUI_MODULEDIR path
# CEGUI uses lib64 on some systems, so we'll add that too
if [ "$prefix" != "@prefix@" ]; then
  prefix_arg="--prefix $prefix"
  export LD_LIBRARY_PATH=$prefix/lib64:$prefix/lib:$prefix@CEGUI_MODULE_SUBDIR@${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}
else
  prefix_arg=
  export LD_LIBRARY_PATH=@prefix@/lib64:@prefix@/lib:@CEGUI_MODULEDIR@${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}
fi

cd $bindir

if [ $debugging = 1 ] ; then
  # Execute real ember binary
  echo "Starting Ember in debugger...."
  gdb --batch -ex "run" -ex "backtrace" -ex "quit" \
  --args $bindir/ember.bin $prefix_arg --config general:logginglevel verbose $orig_args
else
  # Execute real ember binary
  exec $bindir/ember.bin $prefix_arg $orig_args
fi
