#!/bin/sh
# script to start Rserve with the configuration FastRWeb/conf/rserve.conf
# add -d if you want to start the debugging version
#
# honored environment variables:
# ROOT     - root of the RCloud installation (mandatory, although there is a feeble fallback attempt)
# RBIN     - path to R binary to be run (optional, default is "R")

if [ -z "$ROOT" ]; then ## some auto-detection if ROOT is not set...
    for c in /data/rcloud /data/ws /var/www/ws /var/FastRWeb /data/FastRWeb "`pwd`"; do
	if [ -e "$c/conf/rserve.conf" ]; then
	    ROOT="$c"
	    break
	fi
    done
fi

if [ -z "$ROOT" ]; then
    echo '' >&2
    echo ' ERROR: cannot determine ROOT - please set accordingly' >&2
    echo '' >&2
    exit 1
fi
export ROOT

: ${RBIN=R}

if [ "$1" = -h ]; then
   echo ''
   echo " Usage: $0 [-d]"
   echo ''
   echo ' You may need to set ROOT and optionally RBIN accordingly'
   echo ''
   exit 0
fi

if [ "$1" = -d ]; then
   export DEBUG=1
fi

## those that choose to use the RCloud Rlib shall be supported ...
: ${R_LIBS="$ROOT/Rlib"}
export R_LIBS

## create run directory for the PID file if it doesn't exist
if [ ! -d "$ROOT/run" ]; then
    mkdir "$ROOT/run"
fi

if grep -i '^rserve.socket:' "$ROOT/conf/rcloud.conf" >/dev/null 2>&1; then
    echo "NOTE: starting proxified version of RCloud"
    "$RBIN" --slave --no-restore --vanilla --file="$ROOT/conf/run_rcloud.R" --args "$ROOT/conf/rserve-proxified.conf"
else
    "$RBIN" --slave --no-restore --vanilla --file="$ROOT/conf/run_rcloud.R" --args "$ROOT/conf/rserve.conf"
fi
