The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.
use ExtUtils::MakeMaker;
use ExtUtils::Liblist qw();
use Config;

# Attempt to avoid the incorrect 'FAIL' reports from Chris Williams' broken NetBSD smoker(s).
# Comment out the 'exit 0;' (26 lines further down) if this causes problems.

if($Config{osname} eq 'netbsd') {

  my($inc, $cc) = ('', undef);

  if(@ARGV) {
    for my $arg(@ARGV) {
      $inc = (split /=/, $arg)[1] if $arg =~ /^inc=/i;
      $cc = (split /=/, $arg)[1] if $arg =~ /^cc=/i;
    }
  }

  $inc =~ s/'//g;
  $inc =~ s/"//g;

  unless(defined($cc)) {
    $cc = defined($Config{cc}) ? $Config{cc} : 'cc';
  }

  my $opt = $Config{optimize};

  my $out = `$cc $opt $inc $Config{ccflags} -o quad.exe -x c quad.in 2>&1`;

  if($out =~ /quadmath\.h: No such file or directory/i) {
    print "Aborting: Got\n$out\n";
    exit 0;
  }
}

my $defines = $] < 5.008 ? "-DOLDPERL" : "-DNEWPERL";

$defines .= $Config{byteorder} =~ /^1234/ ? " -DWE_HAVE_LENDIAN" : " -DWE_HAVE_BENDIAN";

$defines .= " -DLONGLONG2IV_IS_OK"
  if $Config{ivsize} >= $Config{longlongsize};

$defines .= " -DLONG2IV_IS_OK"
  if $Config{ivsize} >= $Config{longsize};

# Default version of Liblist strips -l params it can't find
# in lib-path, which strips -l params that might be "compiler provided"
# https://github.com/Perl-Toolchain-Gang/ExtUtils-MakeMaker/issues/277
# https://rt.cpan.org/Ticket/Display.html?id=116520
#
# This simply assumes any such stripping is wrong and optimisitically reinserts them.
if ( defined &ExtUtils::Liblist::ext ) {
  warn "Patching ExtUtils::Liblist::ext\n";
  my $orig = \&ExtUtils::Liblist::ext;
  no warnings 'redefine';
  *ExtUtils::Liblist::ext = sub {
      my ( @result ) = $orig->(@_);
      # Always make sure -lm is there as we anchor in front of -lm
      if ( $result[2] !~ /-lm/ ) {
        warn "Reinserting stripped -lm\n";
        $result[2] .= ' -lm';
      }
      # Then insert -lquadmath in front of any such -lm
      if ( $result[2] !~ /-lquadmath/ ) {
        warn "Reinsterting stripped -lquadmath\n";
        $result[2] =~ s{-lm}{-lquadmath -lm};
      }
      return @result;
  };
}

my %options = %{
{
  NAME => 'Math::Float128',
  DEFINE => $defines,
  LIBS => [
    '-lquadmath -lm'
  ],
  INC => '',
  LICENSE  => 'perl',
  VERSION_FROM => 'Float128.pm',
  clean   => { FILES => 'quad.exe' },
  META_MERGE => {
   'meta-spec' => { version => 2 },
    resources => {
      repository => {
        type => 'git',
        url => 'https://github.com/sisyphus/math-float128.git',
        web => 'https://github.com/sisyphus/math-float128',
      },
    },
  },
}
};
WriteMakefile(%options);

# Remove the Makefile dependency. Causes problems on a few systems.
sub MY::makefile { '' }