#!/bin/bash

GO_ROOT=$(cd "$(dirname "$0")/../../.." > /dev/null && pwd)
JRUBY_BASE="$GO_ROOT/tools/jruby"
SERVER_ROOT="${GO_ROOT}/server"
RAILS_ROOT="${SERVER_ROOT}/webapp/WEB-INF/rails.new"

export GEM_HOME="$RAILS_ROOT/vendor/bundle/jruby/1.9"
export GEM_PATH="$JRUBY_BASE/lib/ruby/gems/shared:${GEM_HOME}"
export PATH=$JRUBY_BASE/bin:$PATH

if [ -f "${SERVER_ROOT}/target/go-system-properties" ]; then
    source "${SERVER_ROOT}/target/go-system-properties"
fi

# remove and backup any classpath arguments to merge with `go-system-properties` later
i=0
argv=()
combined_classpath=""
watch_for_classpath=0

for arg in "$@"; do
    if [ "$arg" == '-J-cp' ]; then
        watch_for_classpath='1'
    elif [ "$arg" == '-J-classpath' ]; then
        watch_for_classpath='1'
    elif [ "$watch_for_classpath" == '1' ]; then
        combined_classpath="${combined_classpath}:${arg}"
        watch_for_classpath='0'
    else
        argv[$i]="$arg"
        i=$((i + 1))
    fi
done

combined_classpath="${combined_classpath}:${GO_DEPENDENCY_CLASSPATH}"

IFS=':' read -a combined_classpath_items <<< "${combined_classpath}"

if command -v drip >/dev/null 2>&1 ; then
    export DRIP_INIT_CLASS=org.jruby.main.DripMain
    export JAVACMD=$(which drip)
fi

export JRUBY_OPTS="${JRUBY_OPTS} -J-XX:+TieredCompilation -J-XX:TieredStopAtLevel=1 -J-Djruby.compat.version=2.0 -J-Djruby.compile.invokedynamic=false -J-Djruby.compile.mode=OFF"

jruby_cp=$(echo ${combined_classpath_items[@]} | awk ' !x[$0]++' | tr ' ' ':')

if [ -z "${jruby_cp}" ]; then
    ${JRUBY_BASE}/bin/jruby "${argv[@]}"
else
    ${JRUBY_BASE}/bin/jruby -J-cp "${jruby_cp}" "${argv[@]}"
fi
