def fail_gracefully(message)
  warn "#{message}. Failing gracefully ..."
  exit
end

unless RUBY_ENGINE == 'ruby'
  fail_gracefully "C extensions for #{RUBY_ENGINE} currently not supported"
end

begin
  require "mkmf"
rescue LoadError
  fail_gracefully "mkmf is not installed"
end

MAKE = $make # set by mkmf
       
def make(target=nil)
  if target then sh(MAKE,target)
  else           sh(MAKE)
  end
end

CRCS  = Dir['crc*']
DLEXT = MakeMakefile::CONFIG['DLEXT']

CRCS.each do |crc|
  crc_ext = "#{crc}_ext"

  file "#{crc}/Makefile" => "#{crc}/extconf.rb" do
    Dir.chdir(crc) do
      unless ruby('-S', 'extconf.rb')
        fail_gracefully "extconf.rb failed"
      end
    end
  end

  crc_ext_lib = "#{crc}_ext.#{DLEXT}"

  file "#{crc}/#{crc_ext_lib}" => "#{crc}/Makefile" do
    Dir.chdir(crc) do
      make 'clean'

      unless make
        fail_gracefully "Unable to build C extensions"
      end
    end
  end

  task :default => "#{crc}/#{crc_ext_lib}"
end
