#!/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.

JRUBY = File.expand_path('../..', __FILE__)
TRUFFLEJAR = "#{Dir.home}/.m2/repository/com/oracle/truffle/0.7/truffle-0.7.jar"

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

java_flags = []
rest = []

ARGV.concat ENV["JRUBY_OPTS"].to_s.split(' ')
ARGV.each { |arg|
  if arg.start_with?("-Xmx") or arg == "-ea"
    java_flags << arg
  elsif arg.start_with?("-J")
    java_flags << arg[2..-1]
  elsif arg.start_with?("-Xtruffle.")
    java_flags << "-Djruby.#{arg[2..-1]}"
  else
    rest << arg
  end
}

bootclasspath = []
classpath = []

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

args = [java]
args << "-Djffi.boot.library.path=#{JRUBY}/lib/jni"
args << "-Xbootclasspath/a:" + bootclasspath.join(':')
args << "-cp" << 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)
