use strict;
use warnings;
use Module::Build;


use Config;

# a pair of routines that generates clib/this_machine.h (this code
# obsoletes the gen_this_machine.c program in ctest/ directory)
sub find_right_type {
  my $size=shift;
  if ($Config{shortsize} == $size) {
    return "short";
  } elsif ($Config{intsize}  == $size) {
    return "int";
  } elsif ($Config{longsize} == $size) {
    return "long";
  } elsif (exists($Config{d_longlong}) and
           $Config{d_longlong} eq "HAS_LONG_LONG" and
           $Config{longlongsize} == $size) {
    return "long long";
  } else {
    return 0;
  }
}

sub gen_this_machine_h {

  my $ptrsize = $Config{ptrsize};
  my $matching = find_right_type($ptrsize);

  if ($matching) {
    my $build_dir = $0;
    $build_dir = "./clib" unless $build_dir =~ s|^(.*)/(.*)|$1/clib|;

    die "directory $build_dir is missing!\n" unless -d $build_dir;

    open (OUT, ">${build_dir}/this_machine.h") or
      die "Failed to write this_machine.h output file\n";
    print OUT "// This file is automatically generated! Any edits may be lost!\n\n";
    print OUT "typedef unsigned $matching int native_register_t;\n";
    close OUT;

  } else {
    warn "Couldn't find a C data type on this machine with $ptrsize bytes\n";
    warn "You will have to edit the file clib/this_machine.h manually\n";
    warn "Then re-run with USE_CUSTOM_TYPEDEF as the first parameter\n";
    exit 0;
  }

}

if (@ARGV > 0 and $ARGV[0] =~ "USE_CUSTOM_TYPEDEFS") {
  warn "OK, skipping attempt to divine proper typedef from \$Config\n";
  shift @ARGV;
} else {
  gen_this_machine_h;
  print "Created clib/this_machine.h\n";
}

my $builder = Module::Build->new(
    module_name         => 'Net::OnlineCode',
    license             => 'gpl',
    dist_author         => q{Declan Malone <idablack@users.sourceforge.net>},
    dist_version_from   => 'lib/Net/OnlineCode.pm',
    dist_abstract       => 'A rateless forward error correction scheme',
    configure_requires => {
			   'Module::Build' => 0.40,
			  },
    build_requires => {
        'Module::Build'      => '0.40', # XS
	'ExtUtils::CBuilder' => 0,      # XS
        'Test::More'         => 0,
    },
    add_to_cleanup      => [ 'Net-OnlineCode-*' ],
    create_makefile_pl  => 'traditional',
    # More XS support:
    xs_files            => {
	"lib/Net/OnlineCode.xs"  => "lib/Net/OnlineCode.xs",
    },
    c_source            => "clib/",
    extra_compiler_flags => '-Iclib',
    #extra_linker_flags  => "-lrt", # for benchmark (clock_gettime)
);

$builder->create_build_script();
