#!/bin/sh
# Shell wrapper for rkward executable.

## make sure, we always run in a tty. Otherwise R would go into non-interactive mode and behaves strangely.
## this can be removed later. For R versions 2.3.0 and greater, we set R_Interactive from C
if tty -s; then
  :
else
  # not on a tty? Try to invoke a suitable xterm
  if [ -z $RKWARD_NORECURSE ]; then
    for xtrm in konsole x-terminal-emulator xterm
    do
      xtrmc=`which $xtrm`
      if [ ! -z $xtrmc -a -x $xtrmc ]; then
        RKWARD_NORECURSE=y $xtrmc -e $0 "$@"
        exit
      fi
    done
  fi
fi

R_HOME_DIR="/usr/lib/R"
export R_binary="$R_HOME_DIR/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
error () {
  echo "ERROR: $*" >&2
  exit 1
}

debugger=
args=
while test -n "${1}"; do
  case ${1} in
    --debugger)
      if test -n "`echo ${2} | sed 's/^-.*//'`"; then
        debugger="${2}"; shift
      else
        error "option '${1}' requires an argument"
      fi
      ;;
    *)
      args="${args} ${1}" ;;
  esac
  shift
done

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

## Start rkward. Running through R CMD to set all the relevant R enviroment variables
exec $R_binary CMD $debugger $0.bin ${args}
