#!/usr/bin/env jruby

# Copyright (c) 2016 Oracle and/or its affiliates. All rights reserved.
# This code is released under a tri EPL/GPL/LGPL license. You can use it,
# redistribute it and/or modify it under the terms of the:
#
# Eclipse Public License version 1.0
# GNU General Public License version 2
# GNU Lesser General Public License version 2.1

# A compiler for JRuby+Truffle C extensions

require 'yaml'

SULONG_DIR = ENV['SULONG_DIR']

unless SULONG_DIR
  abort 'You need to set SULONG_DIR to the location of a built checkout of the Sulong repository'
end

def mx(command, *args)
  command = "mx -p #{SULONG_DIR} --vm server #{command} #{args.join(' ')}"
  puts "$ #{command}"
  `#{command}`
end

CEXT_DIR = ARGV[0]

unless CEXT_DIR
  abort 'You need to pass the directory of a C extension so I can build it'
end

CONFIG_FILE = File.join(CEXT_DIR, '.jruby-cext-build.yml')

unless File.exist?(CONFIG_FILE)
  abort "There is no .jruby-cext-build.yml in this C extension at the moment - I don't know how to build it"
end

CONFIG = YAML.load_file(CONFIG_FILE)

SRC = Dir[File.join(CEXT_DIR, CONFIG['src'])]
OUT = File.expand_path(CONFIG['out'], CEXT_DIR)

LL = []

SRC.each do |src|
  ll = File.join(File.dirname(OUT), File.basename(src, '.*') + '.ll')
  mx 'su-clang', "-I#{SULONG_DIR}/include", '-Ilib/ruby/truffle/cext', '-S', '-emit-llvm', src, '-o', ll
  mx 'su-opt', '-S', '-mem2reg', ll, '-o', ll
  LL.push ll
end

mx 'su-link', '-o', OUT, *LL
