################################# setup
require 'rbconfig'
ruby = RbConfig::CONFIG['ruby_install_name']
unless File.exists?('./ext/ffi_c/Makefile')
  system("cd ext/ffi_c && #{ruby} extconf.rb") or raise("Failed configuring extension")
end
system("cd ext/ffi_c && make") or raise("Failed building extension")
unless File.exists?('./build/libtest.so')
  system("make -f libtest/GNUmakefile") or raise("Failed building test library")
end

$LOAD_PATH << 'lib'
$LOAD_PATH << 'ext/ffi_c'

################################# actual test code
require 'ffi'

module LibTest
  extend FFI::Library
  ffi_lib './build/libtest.so'
  attach_function :pack_varargs, [ :buffer_out, :string, :varargs ], :void
end

$status = 0
def check(got, expected)
  puts "Expected #{expected}, got #{got}"
  $status += 1 if expected != got
end

params = [:int, 100, :double, 1.5, :float, 2.7]
buf = FFI::Buffer.new :long_long, 3
LibTest.pack_varargs(buf, 'idf', *params)
check buf.get_int64(0), 100
check buf.get_float64(8), 1.5
check buf.get_float64(16), 2.7

if ($status == 0)
  exec('ruby -S rspec -Ilib -Iext/ffi_c spec/')
else
  puts 'Skipping the entire test suite since the basic tests failed'
  exit($status)
end
