#!/usr/bin/env bash

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
bin_dir="$( cd -P "$( dirname "$source" )" && pwd )"
parent_bin_dir="$( dirname "$bin_dir" )"

VM_ARGS=()
PROGRAM_ARGS=()

NODE_DIR="--nodedir=${parent_bin_dir}"

JVM_USED=0
TRUFFLE_FUNCTION_INLINING_SET=0
TRUFFLE_COMPILATION_THRESHOLD_SET=0

for opt in "${@:1}"; do
    case "${opt}" in
        --nodedir=*)
            NODE_DIR="${opt}" ;;
        --vm*)
            VM_ARGS+=("${opt}") ;;
        --jvm*)
            VM_ARGS+=("${opt}")
            JVM_USED=1 ;;
        --native*)
            VM_ARGS+=("${opt}") ;;
        *)
            PROGRAM_ARGS+=("${opt}") ;;
    esac

    if [[ "${opt}" =~ "TruffleFunctionInlining" ]]; then
        TRUFFLE_FUNCTION_INLINING_SET=1
    fi
    if [[ "${opt}" =~ "TruffleCompilationThreshold" ]]; then
        TRUFFLE_COMPILATION_THRESHOLD_SET=1
    fi
done

# if the user didn't set TruffleFunctionInlining and/or TruffleCompilationThreshold
# explicitly, disable it; this improves npm performance quite significantly
if [[ $JVM_USED == 1 ]]; then
    # in JVM mode, both options need to be set for best performance
    if [[ $TRUFFLE_FUNCTION_INLINING_SET == 0 ]]; then
        VM_ARGS+=("--vm.Dgraal.TruffleFunctionInlining=false")
    fi
    if [[ $TRUFFLE_COMPILATION_THRESHOLD_SET == 0 ]]; then
        VM_ARGS+=("--vm.Dgraal.TruffleCompilationThreshold=10000")
    fi
else
    # in native mode, only TruffleFunctionInlining needs to be deactivated
    if [[ $TRUFFLE_FUNCTION_INLINING_SET == 0 ]]; then
        VM_ARGS+=("--vm.XX:-TruffleFunctionInlining")
    fi
fi

PATH="${bin_dir}:$PATH"

if [ "$(uname -s)" == "SunOS" ]; then
    # node packages typically expect to run with gnu tools
    if [ "${GNU_BINDIR}x" == "x" ]; then
        GNU_BINDIR="/usr/gnu/bin"
    fi
    PATH="${GNU_BINDIR}:${PATH}"
    # Use GCC instead of Solaris Studio Compiler
    export CC="gcc"
    export CXX="g++"
    export CFLAGS="-m64 -U__EXTENSIONS__"
    export CXXFLAGS="$CFLAGS"
    export LDFLAGS="-m64"
fi
export PATH

exec "${bin_dir}/node" "${VM_ARGS[@]}" "${parent_bin_dir}/npm/bin/npm-cli.js" "${NODE_DIR}" "${PROGRAM_ARGS[@]}"
