#!/usr/bin/env 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__)

# Handle missing $HOME variable
home = Dir.home rescue "/home/#{`whoami`.chomp}"

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

TRUFFLE_VERSION = File.foreach("#{JRUBY}/truffle/pom.rb") { |line|
  break $1 if /'truffle\.version' => '((?:\d+\.\d+|\h+)(?:-SNAPSHOT)?)'/ =~ line
}

TRUFFLEJARS = %W[
  com/oracle/truffle/truffle-api/#{TRUFFLE_VERSION}/truffle-api-#{TRUFFLE_VERSION}.jar
  com/oracle/truffle/truffle-debug/#{TRUFFLE_VERSION}/truffle-debug-#{TRUFFLE_VERSION}.jar
].map { |jar| "#{M2REPO}/#{jar}" }

SNAKEYAMLJAR = "#{M2REPO}/org/yaml/snakeyaml/1.14/snakeyaml-1.14.jar"
ANTLR4JAR = "#{M2REPO}/org/antlr/antlr4-runtime/4.5.1-1/antlr4-runtime-4.5.1-1.jar"
JLINE = "#{M2REPO}/jline/jline/2.11/jline-2.11.jar"

GRAAL_OPTIONS_PREFIX = "graal."

VERIFY_JRUBY = false

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

java_flags = []
rest = []
extra_classpath = []

parse_options = lambda do |args|
  until args.empty?
    case arg = args.shift
    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-(cp|classpath)$/
      extra_classpath << args.shift
    when /^-J/
      java_flags << arg[2..-1]
    when /^-Xtruffle\./
      java_flags << "-Djruby.#{arg[2..-1]}"
    else
      rest << arg
    end
  end
end

parse_options.call(ARGV)
parse_options.call(ENV["JRUBY_OPTS"].to_s.split(' '))

bootclasspath = []
classpath = []

bootclasspath << "#{JRUBY}/lib/jruby.jar"
# add other jars in lib to classpath for command-line execution
ignore = %w[jruby.jar jruby-truffle.jar jruby-complete.jar]
Dir.glob("#{JRUBY}/lib/*.jar") { |jar|
  basename = File.basename(jar)
  unless ignore.include?(basename)
    classpath << jar
  end
}

if rest.include?('-X+T')
  bootclasspath += TRUFFLEJARS
  classpath << SNAKEYAMLJAR
  classpath << ANTLR4JAR
  classpath << JLINE
  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

classpath += extra_classpath

args = [java]
args << "-Xss2048k"
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

if args.include?('-d')
  puts args.join(' ')
end

exec(*args)
