#!/bin/sh

# R compile wrapper-script for 'compile.sh'.
# See that script for syntax and more info.
#
# This script does not actually "compile" the source, but writes a
# shell script that will function as the executable: when called, it
# will execute the source with the correct interpreter syntax, thus
# allowing this interpreted source to be used transparently as if it
# was compiled to a standalone binary.
#
# This script requires that Rscript is installed in the chroot.

DEST="$1" ; shift
MEMLIMIT="$1" ; shift
MAINSOURCE="${ENTRY_POINT:-$1}"

# Report the entry point, so it can be saved, e.g. for later replay:
if [ -z "$ENTRY_POINT" ]; then
    echo "Info: detected entry_point: $MAINSOURCE"
fi

# Check if entry point is valid
if [ ! -r "$MAINSOURCE" ]; then
    echo "Error: main source file '$MAINSOURCE' is not readable" >&2
    exit 1
fi

# Check syntax
#
# Store intermediate files in the current dir (/compile) as its only
# available during compilation step.
TMPDIR=`pwd`
export TMPDIR
for f in "$@"
do
    Rscript -e "parse('$f')"
    EXITCODE=$?
    [ "$EXITCODE" -ne 0 ] && exit $EXITCODE
done

# Write executing script:
cat > "$DEST" <<EOF
#!/bin/sh
# Generated shell-script to execute R interpreter on source.

# Detect dirname and change dir to prevent class not found errors.
if [ "\${0%/*}" != "\$0" ]; then
	cd "\${0%/*}"
fi

# Uncomment the line below if you want it make easier for teams to do local
# debugging.
# export ONLINE_JUDGE=1 DOMJUDGE=1

# Rscript needs a temporary directory which is a security risk.
# To make the language work you'll need to set DOMJUDGE_CREATE_WRITABLE_TEMP_DIR=1
# as environment variable when starting the judgedaemon:
# DOMJUDGE_CREATE_WRITABLE_TEMP_DIR=1 bin/judgedaemon

exec Rscript "$MAINSOURCE" "\$@"
EOF

chmod a+x "$DEST"

exit 0
