require "mkmf"
$configure_args["--with-hdf5-dir"] = ENV["HDF5_DIR"]
$configure_args["--with-hdfeos5-lib"] = ENV["HE5_HDF_LIBDIR"]
$configure_args["--with-hdfeos5-include"] = ENV["HE5_HDF_INCDIR"]

require "rbconfig" unless defined? RbConfig
$vendorarchdir=RbConfig::CONFIG['vendorarchdir']
$archlibdir=RbConfig::CONFIG['archlibdir']

dir_config('narray',$vendorarchdir,$vendorarchdir)

if ( ! ( have_header("narray.h") && have_header("narray_config.h") ) ) then
print <<EOS
** configure error **
   Header narray.h or narray_config.h is not found. If you have these files in
   /narraydir/include, try the following:

   % ruby extconf.rb --with-narray-include=/narraydir/include

EOS
   exit(-1)
end

dir_config('gctp', $archlibdir, $archlibdir)
if ( ! have_library("gctp") ) then
  print <<-EOS
  ** configure error **
  EOS
  exit(-1)
end

dir_config('hdf5',$archlibdir,$archlibdir)

if ( ! ( have_header("hdf5.h") && have_library("hdf5")  ) )then
  print <<-EOS
    ** configure error **
       Header hdf.h or the compiled hdf5 library is not found.
       If you have the library installed under /hdf5dir (that is, hdf5.h is
       in /hdf5dir/include and the library in /hdf5dir/lib/),
       try the following:

       % ruby extconf.rb --with-hdf5-dir=/hdf5dir

       Alternatively, you can specify the two directory separately
       with --with-hdf5-include and --with-hdf5-lib.
  EOS
  exit(-1)
end

dir_config('hdfeos5','/usr/include/hdf-eos5',$archlibdir)

if ( ! ( have_header("HE5_HdfEosDef.h") && have_library("he5_hdfeos")  ) )then
  print <<-EOS
    ** configure error **
       Header hdfeos5.h or the compiled hdfeos5 library is not found.
       If you have the library installed under /hdfeos5dir (that is, hdfeos5.h is
       in /hdfeos5dir/include and the library in /hdfeos5dir/lib/),
       try the following:

       % ruby extconf.rb --with-hdfeos5-dir=/hdfeos5dir

       Alternatively, you can specify the two directory separately
       with --with-hdfeos5-include and --with-hdfeos5-lib.
  EOS
  exit(-1)
end

if /cygwin|mingw/ =~ RUBY_PLATFORM
   have_library("narray") || raise("ERROR: narray library is not found")
end

create_makefile "numru/hdfeos5raw"

######  Modify Makefile: #######
File.rename("Makefile","Makefile.orig")
oldmkfl = File.open("Makefile.orig")
newmkfl = File.open("Makefile","w")
oldmkfl.each_line{ |line|
   case(line)
   when /^distclean:/
      newmkfl.puts(line)
      newmkfl.puts("\t\t@$(RM) *.he5  Makefile.orig")
   when /^all:/
      newmkfl.puts(line)
      newmkfl.puts("")
      newmkfl.puts("test: all")            # insert the "test" target
      newmkfl.puts("\t\t@cd test && ruby test.rb && echo 'test did not fail :-p (please ignore the warnings)' && cd ..")
   else
      newmkfl.puts(line)
   end
}
newmkfl.close
