require File.join(File.dirname(__FILE__), '..', '..', 'lib', 'coo-coo', 'platform')

NVCC = ENV.fetch("NVCC", "nvcc")
NVCCFLAGS = Array.new
NVCCFLAGS << "-g" if ENV['DEBUG']

if CooCoo::Platform.windows?
  #NVCCFLAGS="--cl-version=2015"
else
  NVCCFLAGS << "--compiler-options='-fPIC -Wall'"
end

DLEXT=RbConfig::CONFIG['DLEXT']

task :default => [ "buffer.#{DLEXT}", "buffer_ffi.rb", "matrix_ffi.rb" ]

task :clean do
  sh("rm -f buffer.#{DLEXT} buffer.ext buffer.lib buffer.cu buffer.h buffer_ffi.rb matrix.cu matrix.h matrix_ffi.rb")
end

desc "Build buffer.#{DLEXT}"
file "buffer.#{DLEXT}" => [ 'buffer.cu', 'matrix.cu' ] do |t|
	sh("#{NVCC} #{NVCCFLAGS.join(' ')} -shared -o #{t.name} #{t.sources.join(' ')}")
end

def ffi_gen(*args)
  ruby(File.join(CooCoo.root, 'bin', 'ffi-gen'), *args)
end

def ffi_file(target)
  file "#{target}.cu" => [ "#{target}.pre.cu", "#{target}.h" ] do |t|
    ffi_gen('--source', '-o', t.name, t.source)
  end

  file "#{target}.h" => "#{target}.pre.cu" do |t|
    ffi_gen('--header', '-o', t.name, *t.sources)
  end

  file "#{target}_ffi.rb" => "#{target}.pre.cu" do |t|
    ffi_gen('--ffi',
            '--module', "CooCoo::DeviceBuffer",
            '--library', 'buffer',
            '-t', 'int=cudaError_t',
            '-o', t.name,
            *t.sources)
  end
end

ffi_file 'buffer'
ffi_file 'matrix'
