#!/bin/sh
# Shell wrapper for rkward executable.
error () {
  echo "ERROR: $*" >&2
  exit 1
}

export R_binary="/usr/bin/R"

## Location of R may have moved, so check
if test -x "${R_binary}"; then
  :
else
  error "R binary ('${R_binary}') not found. Most likely your installation of R has moved to a new location. Please rebuild rkward."
fi

## Apparently on some systems an embedded R gets outsmarted somehow, and LC_NUMERIC is set to some dangerous value for the whole app (via SCIM)
## To prevent this, set it here, explicitely. R does not work with wrong settings of LC_NUMERIC.

## First, however, need to unset LC_ALL, if set. Instead we set LANG, so the default will be the same, where not overridden
if [ -z "$LC_ALL" ]; then
  :
else
  export LANG="$LC_ALL"
  unset LC_ALL
  echo "Warning: unsetting LC_ALL"
fi

# handle --debugger argument (if any)
# the loop partially copied from the R wrapper script
debugger=
if [ "${1}" = "--debugger" ]; then
  shift
  if [ -z "${1}" ]; then
    error  "option '--debugger' requires an argument"
  else
    debugger=${1}
    shift
  fi
fi

## set LC_NUMERIC to "C"
export LC_NUMERIC="C"

## Start rkward. Running through R CMD to set all the relevant R enviroment variables
if test -x "`dirname $0`/rkward.frontend" ; then
  # for running directly from a build directory. Don't use this, unless you are a developer!
  rkward_binary="`dirname $0`/rkward.frontend"
else
  # for regular installations
  export RKWARD_ENSURE_PREFIX="`dirname $0`/.."
  rkward_binary="/usr/lib/kde4/libexec/rkward.frontend"
fi
exec $R_binary CMD $debugger ${rkward_binary} "$@"
