#------------------------------------------------------------------------
# (The MIT License)
# 
# Copyright (c) 2008-2011 Rhomobile, Inc.
# 
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
# 
# http://rhomobile.com
#------------------------------------------------------------------------

# Builds rubylinux executable

cc = "gcc"
cflags = "-O2 -g -Wall -Wno-parentheses"
lnk_flags = "-L. -rdynamic -Wl,-export-dynamic"
incl = "-I../shared/ruby -I../shared/ruby/linux -I../shared/ruby/include -I../shared/ruby/generated -I../shared -I../shared/ruby/rhoruby -I../shared/sqlite"
compile = "#{cc} #{cflags} #{incl} -DRUBYLINUX -DRUBY_EXPORT -c "
link = "#{cc} #{lnk_flags}"
target = "target/compiler/rubylinux"
out = "-lpthread -lrt -ldl -lcrypt -lm -o #{target}"
src_dir = "../shared"
code = true
objfiles = []

task :default => :all

desc "Build all ruby sources"
task :all, :continue do |t,args|
  mkdir_p "obj" unless File.exists? "obj"
  File.open("files.txt").each_line do |file|
    file.chomp!
    s_file = "#{src_dir}/#{file}.c"
	o_file = "obj/#{File.basename file}.o"
    objfiles << "#{o_file}"
    if not uptodate?("#{o_file}", "#{s_file}")
      cmd = "#{compile} -o #{o_file} #{s_file}"
      puts cmd
      code = system cmd
    end
    abort("Aborting due to compile errors...") if not code and not args.continue
  end
  
  if not uptodate?(target, objfiles)
    cmd = "#{link} #{objfiles.join(" ")} #{out}"
    puts cmd
    code = system cmd
    abort("Aborting due to link errors...") if not code

    cp_r target, "../../res/build-tools"
  end
end

desc "Clean all artifacts"
task :clean do
  rm_rf "obj"
end
