#!/usr/bin/env bash
#
# Copyright (c) 2018, 2023, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3 only, as
# published by the Free Software Foundation.
#
# This code is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# version 3 for more details (a copy is included in the LICENSE file that
# accompanied this code).
#
# You should have received a copy of the GNU General Public License version
# 3 along with this work; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
# or visit www.oracle.com if you need additional information or have any
# questions.
#

# This script is deployed under {GRAALVM_HOME}/languages/R/bin/Rscript in
# legacy GraalVM layout, or under {FASTR_HOME}/bin/Rscript in FastR JVM
# standalone.
#
# It forwards to the RMain launcher, which is a regular Graal SDK thin launcher

source="${BASH_SOURCE[0]}"
while [ -h "$source" ] ; do
    prev_source="$source"
    source="$(readlink "$source")";
    if [[ "$source" != /* ]]; then
        # if the link was relative, it was relative to where it came from
        dir="$( cd -P "$( dirname "$prev_source" )" && pwd )"
        source="$dir/$source"
    fi
done
location="$( cd -P "$( dirname "$source" )" && pwd )"
fastr_home="$( dirname "${location}" )"

# we can invoke FastR directly, but we do have to set R_HOME
export R_HOME="${fastr_home}"

# In GNU-R the Rscript is executable that seems to be setting up LD_LIBRARY_PATH like ldpaths under the hood:
. "${fastr_home}/etc/ldpaths"

exec "${fastr_home}/bin/RMain" Rscript ${FASTR_INTERNAL_ARGS[@]} "$@"
