#!/usr/bin/ruby
# A JRuby launcher, in Ruby, and using the class files from Eclipse
# Currently needs the core and stdlib jar, so build them again when they change.

M2REPO = "#{Dir.home}/.m2/repository"

TRUFFLEJARS = %w[
  /com/oracle/truffle/truffle-api/0.10/truffle-api-0.10.jar
  /com/oracle/truffle/truffle-debug/0.10/truffle-debug-0.10.jar
].map { |jar| "#{M2REPO}/#{jar}" }
SNAKEYAMLJAR = "#{M2REPO}/org/yaml/snakeyaml/1.14/snakeyaml-1.14.jar"
ANTLR4JAR = "#{M2REPO}/org/antlr/antlr4-runtime/4.5/antlr4-runtime-4.5.jar"

GRAAL_OPTIONS_PREFIX = "jvmci.option."

JRUBY = File.expand_path('../..', __FILE__)

VERIFY_JRUBY = false

java = ENV["JAVACMD"] || "java"

java_flags = []
rest = []

ARGV.concat ENV["JRUBY_OPTS"].to_s.split(' ')
ARGV.each { |arg|
  case arg
  when /^-Xmx/, "-ea"
    java_flags << arg
  when /^-J-G:+/
    java_flags << "-D#{GRAAL_OPTIONS_PREFIX}#{$'}=true"
  when /^-J-G:-/
    java_flags << "-D#{GRAAL_OPTIONS_PREFIX}#{$'}=false"
  when /^-J-G:/
    java_flags << "-D#{GRAAL_OPTIONS_PREFIX}.#{$'}"
  when /^-J/
    java_flags << arg[2..-1]
  when /^-Xtruffle./
    java_flags << "-Djruby.#{arg[2..-1]}"
  else
    rest << arg
  end
}

bootclasspath = []
classpath = []

bootclasspath << "#{JRUBY}/lib/jruby.jar"
if rest.include?('-X+T')
  bootclasspath += TRUFFLEJARS
  classpath << SNAKEYAMLJAR
  classpath << ANTLR4JAR
  classpath << "#{JRUBY}/truffle/build.eclipse"
  java_flags << "-Djruby.truffle.core.load_path=#{JRUBY}/truffle/src/main/ruby"
end

unless VERIFY_JRUBY
  bootclasspath += classpath
  classpath.clear
end

args = [java]
args << "-Djffi.boot.library.path=#{JRUBY}/lib/jni"
args << "-Xbootclasspath/a:" + bootclasspath.join(':')
args << "-classpath" << classpath.join(':') unless classpath.empty?

args << "-Djruby.home=#{JRUBY}"
args << "-Djruby.lib=#{JRUBY}/lib"
args << "-Djruby.script=jruby"
args << "-Djruby.shell=/bin/sh"

args += java_flags
args << "org.jruby.Main"
args += rest

exec(*args)
