use strict;
use warnings;

use lib 'inc';
use ExtUtils::CChecker 0.11;
use Module::Build::with::XSTests;

my $MIN_PERL = '5.014'; # PL_keyword_plugin

# MSWin32 needs at least perl 5.22
#   https://rt.cpan.org/Ticket/Display.html?id=136577
$MIN_PERL = '5.022' if $^O eq "MSWin32";

my $cc = ExtUtils::CChecker->new( quiet => 1 );

$cc->try_find_cflags_for(
   cflags => [
      # Most systems will need no extra cflags
      [],
      # HPUX may need to be told +std=gnu in order to accept anon inner unions
      ( $^O eq "hpux" ) ? [ "+std=gnu" ] : (),
   ],
   source => <<'EOF'
struct Named {
   union { int a, b; };
   int c;
};
int main(void) { struct Named n; n.a = 0; return n.a; }
EOF
) or die "OS unsupported - C compiler does not support anonymous inner unions\n";

{
   print "Checking for PL_infix_plugin...\n";

   # Teach $cc how to find and link to libperl
   require Config;
   require Text::ParseWords;

   my @linker_flags = (
      "-L" . File::Spec->catdir($Config::Config{archlibexp}, "CORE"),
      "-lperl", Text::ParseWords::shellwords( $Config::Config{libs} ),
   );

   my $have_pl_infix_plugin = 0;

   $have_pl_infix_plugin = 1 if grep { $_ eq "--have-pl_infix_plugin" } @ARGV;

   $have_pl_infix_plugin ||= $cc->try_compile_run(
      extra_linker_flags => \@linker_flags,
      source => <<'EOF'
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"

int main(void) {
   struct Perl_custom_infix def;
   def.prec = INFIX_PREC_LOW;
   def.build_op = NULL;
   return 0;
}
EOF
   ) if $] >= 5.037007;

   if( $have_pl_infix_plugin ) {
      print "Including support for core perl PL_infix_plugin\n";
      # ->define isn't currently documented but it will be in next version; it
      # has been present since v0.04, basically forever
      $cc->define( "HAVE_PL_INFIX_PLUGIN" )
   }
}

my $build = Module::Build::with::XSTests->new(
   module_name => 'XS::Parse::Keyword',
   requires => {
      'perl' => $MIN_PERL,
   },
   build_requires => {
      # We have multiple t/*.xs files, which requires a new enough version of
      # ExtUtils::ParseXS to cope with.
      # Unsure the exact version required. perl 5.14 normally ships with version
      # 2.2210 but that fails. perl 5.16's version 3.16 works fine.
      'ExtUtils::ParseXS' => '3.16',
   },
   test_requires => {
      'Test::More' => '0.88', # done_testing
   },
   configure_requires => {
      'ExtUtils::CChecker' => '0.11',
      'Module::Build' => '0.4004', # test_requires
   },
   license => 'perl',
   create_license => 1,
   create_readme  => 1,

   extra_compiler_flags => [qw( -I. -Ihax )],
   c_source => [ "src/" ],
);

$cc->extend_module_build( $build );
$build->notes( builder_cflags => $cc->extra_compiler_flags );

$build->create_build_script;
