#!/usr/bin/perl -w
#
# cpan2rpm - tool to convert tgz files to rpms, if CPAN rules are
# adhered to.
#
# TODO:
#  - add command line switch to separate tasks of generating spec file
#    vs building the rpm
#  - add command line switch for specifying release number

use strict;
use FileHandle;

my $tgz = shift(@ARGV);

my $srcdir = "/tmp/$$.src";
my $instdir = "/tmp/$$.inst";

mkdir ($srcdir, 0755) || die;
mkdir ($instdir, 0755) || die;

system("tar -C $srcdir -zxvf $tgz") && die;

my $pwd = `pwd`; chomp($pwd);
chdir($srcdir) || die;
my $subdir;
{
	my @dir = `ls`; 
  $subdir = $dir[0];
  chomp($subdir);
};
chdir($subdir) || die;

my ($name, $version) = ($subdir =~ m/^(.*)\-([\d\.]+)$/);

# do a test install
system("perl ./Makefile.PL PREFIX=${instdir}");
system("make && make install");

my $description = join("",`cat README*`);

# discover which files want to be installed
chdir($instdir) || die;
my @files = `find . -type f -print`;
# filter files:
@files = grep {!/perllocal.pod$/} @files;
@files = map {s/^\./\/usr/;$_} @files;
my $files = join("",@files);

chdir($pwd);

my $packager = $ENV{USER} . '@' . $ENV{HOSTNAME};
my $date = `date`; chomp($date);
my $rpmname = "perl-${name}";

# generate a spec file
my $specfile = "${name}-${version}.spec";
my $fh = new FileHandle(">${specfile}") || die;
print $fh <<EOT ;
# Spec file generated using cpan2rpm
# generated on $date
# generated by $packager
Summary: perl module $name
Name: $rpmname
Version: $version
Release: 1
Copyright: GPL
Group: Perl/Libraries
Source: $tgz
Packager: $packager

%description
$description

%prep
%setup -n $subdir

%build
perl ./Makefile.PL
make

%install
make install

%files
$files

EOT
$fh->close();

# build the actual rpm
print STDERR "building the rpm...\n";
system("cp $tgz /usr/src/redhat/SOURCES") && die;
system("cp $specfile /usr/src/redhat/SPECS") && die;
system("rpm -ba /usr/src/redhat/SPECS/$specfile") && die;
system("cp /usr/src/redhat/RPMS/i386/${rpmname}-${version}-*.rpm .") && die;
system("cp /usr/src/redhat/SRPMS/${rpmname}-${version}-*.src.rpm .") && die;

# clean up
system("/bin/rm -rf $srcdir $instdir /usr/src/redhat/SOURCES/$tgz /usr/src/redhat/SPECS/$specfile");
