#!/bin/sh

# quake3 or quake3-server or whatever
IOQ3SELF=quake3
# "server" or "client"
IOQ3ROLE=server
# ioquake3 or ioq3ded
IOQ3BINARY=ioq3ded
# q3a or openarena
IOQ3DOTDIR=q3a

BASEPATH="/usr/share/games/quake3"
ENGINE="/usr/lib/ioquake3/${IOQ3BINARY}"

DEBUGGER="$QUAKE3_DEBUGGER"

# the defaults mostly apply
CVARS="+set com_standalone 0"
CVARS="$CVARS +set fs_basepath $BASEPATH"

QUIET=0

EXCUSE="\
Quake III Arena ${IOQ3ROLE} wrapper for Debian\n\
\n\
Usage: ${IOQ3SELF} [OPTION]...\n\
\n\
 -h, --help\t\tDisplay this help\n\
 -q, --quiet\t\tDisable console output\n\
  +<internal command>\tPass commands to the engine\n"

while [ "$1" != "" ]; do
  case "$1" in
    -h|--help)
      echo ${EXCUSE}
      exit 0
      ;;
    -q|--quiet)
      CVARS="$CVARS +set ttycon 0"
      QUIET=1
      ;;
    *)
      break
      ;;
  esac
  shift
done

# sanity check: the engine doesn't cope well with missing data
for i in 0 1 2 3 4 5 6 7 8; do
  if test -f $BASEPATH/baseq3/pak$i.pk3; then
    :
  else
    if test "$IOQ3ROLE" = client; then
      $BASEPATH/need-data.sh $BASEPATH/README.quake3-data
    else
      echo "Quake III Arena data missing, see /usr/share/doc/quake3-server/README.quake3-data"
    fi
    exit 72     # EX_OSFILE
  fi
done

if test "z$QUIET" = z1; then
  exec >/dev/null 2>&1;
fi

if test -n "$QUAKE3_BACKTRACE"; then
  exec gdb -return-child-result -batch -ex run -ex 'thread apply all bt full' -ex kill -ex quit --args ${ENGINE} ${CVARS} "$@"
else
  exec ${DEBUGGER} ${ENGINE} ${CVARS} "$@"
fi
