The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.
# $Id$

# use 5.008;
use ExtUtils::MakeMaker;
use Getopt::Long;

GetOptions(
    'rpmversion=s' => \$rpmv,
    'rebuildh' => \my $rebh,
);

my $rpmheaderlocation;

foreach (qw(
    /usr/include
    /usr/local/include
    )) {
    if (-d "$_/rpm") {
        $rpmheaderlocation = "$_/rpm";
        last;
    }
}

$rpmheaderlocation or die "Can't find rpmheader location";

my $rpmv ||= (`rpm --version` =~ /([\d\.]+)/)[0];
open($FH, "> rpmversion.h") or die "Can't open rpmversion.h";
print $FH "/* File generated by Mafile.PL\n";
print $FH ' * $Id$' ."\n";
print $FH " */\n\n";
print $FH "#ifndef RPMVERSION_H\n#define RPMVERSION_H\n\n";
foreach (qw(
    4.2.0
    4.4.1
    4.4.2
    4.8.0
    4.8.1
    4.9.0
    4.9.1
    4.9.1.1
    4.9.1.2
    )) {
    $v = $_;
    $v =~ s/\./_/g;
    print $FH "#define RPM$v\n";
    $rpmv =~ /^\Q$_/ and last;
}
print $FH "\n#endif\n";
close($FH);
if ($rebh) { exit 0 };

my @rpmconstantfiles = qw(
    rpmconstant.c
    rpmconstant.h
    rpmconstant_internal.c
    rpmh2tbl
    );

my ($obj, $ldd, $fl) =
    -f '/usr/include/rpmconstant/rpmconstant.h' ?
    ('', '-lrpmconstant', '-DHAVE_RPMCONSTANT') :
    ('rpmconstant.o rpmconstant_internal.o rpmconstanttbl.o', '', '');

sub MY::postamble {
        my $first = <<RPMCONSTTBL;
rpmversion.h:
	\$(PERL) Makefile.PL --rebuildh

rpmconstanttbl.c: Makefile rpmh2tbl
	perl rpmh2tbl $rpmheaderlocation/*.h > \$@

RPMCONSTTBL
	# This code is to reduce duplication of files
	# in fact it is only usefull for the maintainers of this module
	# if you get the module from CPAN, those files are allready here
	# if you're building from svn, you need rpmconstant directory
	my $second = "copyrpmconstant: " . join(" ", @rpmconstantfiles) ."\n\n";
	if(-d '../../rpmconstant') {
        foreach (@rpmconstantfiles) {
            $second .= "$_: ../../rpmconstant/$_\n\tcp -a \$< \$@\n\n";
        }
	}

	$first . $second
}

WriteMakefile(
    NAME         => 'RPM4',
    VERSION_FROM => '../lib/RPM4.pm',
    OBJECT       => "RPM4.o RPM4sign.o $obj",
    INC	         => "-I$rpmheaderlocation",
    LIBS         => "-lrpmsign -lrpm -lrpmio -lrpmbuild -lpopt -lz -lbz2 $ldd",
    'CCFLAGS'    => "-Wall $fl",
    depend       => { "RPM4.xs" => join(" ", @rpmconstantfiles) },
);