#!/usr/bin/perl -w
use strict;

use Getopt::Long;
use File::Basename;
use File::Copy;
use Archive::Tar;

use lib '/usr/lib/rpm';
use Specfile;

my %options;

GetOptions(\%options, "outdir=s", "tmpdir=s", "email=s", "name=s", "create", "test", "epoch=n", "version=s", "release=s", "perlver=s", "patch=s", "noarch=s") or die_usage();

my $fullname = shift;

die_usage() unless $fullname;

my $tarball = basename($fullname);
my $create = $options{create} || '';
my $email = $options{email} || (getpwuid($<))[0] . '@redhat.com';
my $outdir = $options{outdir} || './';
my $tmpdir = $options{tmpdir} || '/tmp';
my $noarch = $options{noarch};

$tarball =~ /^(.+)\-([^-]+)\.tar\.gz$/;
my $name = $options{name} || $1;
my $ver = $options{version} || $2;

die "Module name/version not parsable from $tarball" unless $name and $ver;

$name =~ s/::/-/g;

copy($fullname, $tmpdir)
  or die "copy: $!";

$noarch = $options{noarch};

my $patchfile = '';
if ($options{patch}) {
  copy($options{patch}, $tmpdir);
  $patchfile = $options{patch};
}

my $spec = new RPM::Specfile;

my $perlver = "0:5.00503";
if ($options{perlver} and $options{perlver} eq '5.6.1') {
  $perlver = "1:5.6.1";
}

# some basic spec fields
$spec->name("perl-$name");
$spec->version($ver);
$spec->release($options{release} || "8");
$spec->epoch($options{epoch});
$spec->summary("$name Perl module");
$spec->description($spec->summary);
$spec->group("Development/Libraries");
$spec->license("distributable");
$spec->buildrequires("perl >= $perlver");
$spec->packager($email);
$spec->add_changelog_entry($email, 'Specfile autogenerated');

$spec->buildarch('noarch') if $noarch;

# $spec->push_require(q|%(perl -MConfig -le 'if (defined $Config{useithreads}) { print "perl(:WITH_ITHREADS)" } else { print "perl(:WITHOUT_ITHREADS)" }')|);
# $spec->push_require(q|%(perl -MConfig -le 'if (defined $Config{usethreads}) { print "perl(:WITH_THREADS)" } else { print "perl(:WITHOUT_THREADS)" }')|);
# $spec->push_require(q|%(perl -MConfig -le 'if (defined $Config{uselargefiles}) { print "perl(:WITH_LARGEFILES)" } else { print "perl(:WITHOUT_LARGEFILES)" }')|);

$spec->push_source($tarball);
$spec->push_patch(basename($patchfile))
  if $patchfile;

# make a URL that can actually possibly take you to the right place
my $url_name = $name;
$url_name =~ s/-/::/g;
$url_name =~ s/([^a-zA-Z0-9])/sprintf "%%%x", ord $1/ge;
$spec->url("http://search.cpan.org/search?mode=module&query=$url_name");

# now we get into the multiline tags.  stolen mostly verbatim from
# cpanflute1

my $patch = '';
if ($patchfile) {
  $patch = "%patch0 -p1\n";
}

$spec->prep("%setup -q -n $name-%{version} $create\n$patch");
$spec->file_param("-f $name-$ver-filelist");
$spec->push_file("%defattr(-,root,root)");

my $test_clause = '';
$test_clause = "make test" if $options{test};

$spec->build(<<EOB);
CFLAGS="\$RPM_OPT_FLAGS" perl Makefile.PL
make
$test_clause
EOB

$spec->clean('rm -rf $RPM_BUILD_ROOT');
my $inst = q{
rm -rf $RPM_BUILD_ROOT
eval `perl '-V:installarchlib'`
mkdir -p $RPM_BUILD_ROOT/$installarchlib
make PREFIX=$RPM_BUILD_ROOT/usr install

[ -x /usr/lib/rpm/brp-compress ] && /usr/lib/rpm/brp-compress

find $RPM_BUILD_ROOT/usr -type f -print | \
	sed "s@^$RPM_BUILD_ROOT@@g" | \
	grep -v perllocal.pod | \
	grep -v "\.packlist" > $name-$ver-filelist
if [ "$(cat $name-$ver-filelist)X" = "X" ] ; then
    echo "ERROR: EMPTY FILE LIST"
    exit -1
fi
};

$inst =~ s/\$name/$name/g;
$inst =~ s/\$ver/$ver/g;

$spec->install($inst);

# write the spec file.  create some macros.
$spec->write_specfile("$tmpdir/perl-$name.spec");

open FH, ">$tmpdir/macros"
  or die "Can't create $tmpdir/macros: $!";

print FH qq{
%_topdir        $tmpdir
%_builddir      %{_topdir}
%_rpmdir        %{_topdir}
%_sourcedir     %{_topdir}
%_specdir       %{_topdir}
%_srcrpmdir     $outdir
};

close FH;

open FH, ">$tmpdir/rpmrc"
  or die "Can't create $tmpdir/rpmrc: $!";

print FH qq{
include: /usr/lib/rpm/rpmrc
macrofiles: /usr/lib/rpm/macros:$tmpdir/macros
};
close FH;

# perform the build, die on error
my $retval = system "rpm --rcfile $tmpdir/rpmrc -bs --rmsource --rmspec --clean $tmpdir/perl-$name.spec";
$retval = $? >> 8;
if ($retval != 0) {
  die "RPM building failed!\n";
}

unlink "$tmpdir/rpmrc", "$tmpdir/macros";
