verbose(true)
NEED_STRIP = !ENV['DEBUG']
OPTZ_LEVEL = !ENV['DEBUG'] ? '-O3' : '-O0'
DEBUG_FLAG = !ENV['DEBUG'] ? '' : '-g'

task :default => :all
task :all => [:files, :deploy, :sim, :watch_sim, :nfd, :instruments]

STRIP = "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/strip"
CLANG = ENV['CC'] || "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang"

task :files do
  bin = 'ruby'
  install '../vm/miniruby', 'ruby'
  sh "#{STRIP} -x \"#{bin}\"" if NEED_STRIP
end

task :deploy do
  mkdir_p 'ios'
  bin = 'ios/deploy'
  if !File.exist?(bin) or File.mtime('deploy.m') > File.mtime(bin) or File.mtime('builtin_debugger_cmds.h') > File.mtime(bin)
    sh "#{CLANG} -mmacosx-version-min=10.6 -I./src -std=c99 -Wall #{DEBUG_FLAG} #{OPTZ_LEVEL} deploy.m -o \"#{bin}\" -framework Foundation -I."
    sh "#{STRIP} -x \"#{bin}\"" if NEED_STRIP
  end
end

task :sim do
  %w{ios osx}.each do |template|
    mkdir_p template
    bin = File.join(template, 'sim')
    if !File.exist?(bin) or File.mtime('sim.m') > File.mtime(bin) or File.mtime('builtin_debugger_cmds.h') > File.mtime(bin)
      define = "-DSIMULATOR_#{template.upcase}"
      sh "#{CLANG} #{define} -mmacosx-version-min=10.6 -I./src -std=c99 -Wall #{DEBUG_FLAG} #{OPTZ_LEVEL} sim.m -o \"#{bin}\" -framework Foundation -framework ApplicationServices -framework AppKit -L. -ledit -Wl,-rpath,/usr/lib -I."
      sh "#{STRIP} -x \"#{bin}\"" if NEED_STRIP
    end
  end
end

# TODO need to make non-ARC when sharing code with sim.m to load REPL etc.
task :watch_sim do
  bin = 'watch-sim'
  if !File.exist?(bin) or File.mtime('watch-sim.m') > File.mtime(bin) or File.mtime('builtin_debugger_cmds.h') > File.mtime(bin)
    sh "#{CLANG} -mmacosx-version-min=10.8 -fobjc-arc -I./src -std=c99 -Wall #{DEBUG_FLAG} #{OPTZ_LEVEL} watch-sim.m -o \"#{bin}\" -L. -ledit -Wl,-rpath,/usr/lib -I."
    sh "#{STRIP} -x \"#{bin}\"" if NEED_STRIP
  end
end

task :nfd do
  bin = 'nfd'
  if !File.exist?(bin) or File.mtime('nfd.m') > File.mtime(bin)
    sh "#{CLANG} -mmacosx-version-min=10.6 -I./src -std=c99 -Wall #{DEBUG_FLAG} #{OPTZ_LEVEL} nfd.m -o \"#{bin}\" -framework Foundation -I."
    sh "#{STRIP} -x \"#{bin}\"" if NEED_STRIP
  end
end

task :instruments do
  bin = 'instruments'
  src = bin + '.c'
  if !File.exist?(bin) or File.mtime(src) > File.mtime(bin)
    sh "#{CLANG} -mmacosx-version-min=10.6 -std=c99 -Wall #{DEBUG_FLAG} #{OPTZ_LEVEL} #{src} -o \"#{bin}\" -framework CoreFoundation -framework ApplicationServices"
  end
end

task :android => [:files] do
  Dir.chdir '../vm/jit-bridge' do
    sh "rake"
  end
  sh "cp ../vm/jit-bridge/jit-bridge android/repl"
end

task :clean do
  %w{ruby llc ios/deploy ios/sim osx/sim watch-sim ndf instruments}.each { |path| rm_rf(path) }
end
