#!/usr/bin/perl -w

#
#   CPAN module RPM maker
#

use vars qw($VERSION $VX);
$VERSION = "2.013";

# --- prologue ----------------------------------------------------------------

use strict;
use Getopt::Long;
use Sys::Hostname;
use ExtUtils::MakeMaker 5.4302;

my ($RPM, $TMPDIR, %RPMDIR, $CWD, %info, %meta, $Temp);

my $tarRE = q/\.(tar\.(g?z|bz2)|tgz|zip)$/;
my $docRE = '(readme|changes|todo|license|install|\.txt|\.html)';
my $HTTPWARN = 0;   # so we don't repeat warnings

*OLDOUT = *OLDERR = *OLDIN = "";

# --- main() ------------------------------------------------------------------

init();            # initialise stuff
get_mod();         # retrieve a module to work with
get_meta();        # get metadata from tarball
mk_spec();         # create a custom spec file
mk_rpm();          # build the RPM
inst_rpm();        # install it if requested

# --- support functionality ---------------------------------------------------

END {
    chdir $CWD;
    return print("$VERSION\n") if $VX;
    print "-- Done --\n";
    }

sub init {
    $|++;    # good for system()

    chomp($CWD = qx/pwd/);

    $RPM = inpath("rpmbuild");
    $RPM = inpath("rpm") unless $RPM;
    die "Cannot find rpmbuild/rpm in PATH" unless $RPM;

    # package info defaults

    %info = (
        url          => "http://www.cpan.org",
        packager     => "Arix International <cpan2rpm\@arix.com>",
        group        => "Applications/CPAN",
        license      => "Artistic",
        release      => 1,
        buildroot    => "%{_tmppath}/%{name}-%{version}-%(id -u -n)",
        description  => "None.",
        );

    my %desc = (
        # -- simple options
        "name=s"           => "RPM package name",
        "no-prfx"          => "suppresses package name prefix",
        "summary=s"        => "package summary",
        "version=s"        => "override the CPAN version number",
        "release=i"        => "RPM relase number",
        "epoch=i"          => "the package epoch",
        "author=s"         => "author information",
        "packager=s"       => "packager identification",
        "distribution=s"   => "RPM distribution",
        "license=s"        => "licensing information",
        "group=s"          => "RPM group",
        "url=s"            => "home URL",
        "buildroot=s"      => "root directory to use for build",
        "buildarch=s"      => "package architecture",
        "description=s"    => "package description",
        # -- aggregate options
        "requires=s@"      => "packages required for installation",
        "provides=s@"      => "modules provided by the package",
        "buildrequires=s@" => "packages required for building",
        "no-requires=s"    => "suppresses generation of a set of reqs",
        "source|s=s@"      => "specifies (multiple) sources to use",
        "patch|p=s@"       => "specifies (multiple) patches to apply",
        "doc=s"            => "adds to the spec's %doc section",
        # -- section options
        "prologue=s"       => "inserts text at beginning of section",
        "epilogue=s"       => "inserts text at end of section",
        # -- section options
        "spec-only"        => "only generates spec file",
        "spec=s"           => "specifies the name of a spec file",
        "make-maker=s"     => "arguments for makefile creation",
        "make=s"           => "arguments passed to make",
        "make-no-test"     => "suppress running test suite",
        "make-install=s"   => "arguments for make install",
        "find-provides=s"  => "instructs us to use a given filter",
        "find-requires=s"  => "(see man page for further details)",
        "tempdir=s"        => "specify temporary working directory",
        "req-scan-all"     => "scan all files in a tarball for reqs",
        "no-clean"         => "suppress --clean",
        "shadow-pure"      => "override existing pure perl module",
        "install|i"        => "install package when done",
        "force"            => "forces all operations",
        # -- miscellaneous options
        "mk-rpm-dirs=s"    => "creates RPM dirs for non-root users",
        "upgrade"          => "upgrades cpan2rpm",
        "no-upgrade-chk|U" => "no version checks",
        "debug:i"          => "produce debugging output",
        "help|h"           => "this help screen",
        "V"                => "cpan2rpm version",
        "D"                => "runs the perl debugger",
        );

    # get user options
    my %opts = ();
    my @args = grep !/^-D$/, @ARGV;
    my $ret = GetOptions(\%opts, keys %desc);

    exec("$^X -d $0 " . join(" ", @args)) if $opts{D};
    $VX++, exit if $opts{V};

    print "\n-- cpan2rpm - Ver: $VERSION --\n";
    syntax(\%desc) if defined $opts{help} || !$ret;

    # a clarification on the various keys used in %info:
    #   dist     =  user entry of the form <directory>, <tarball-path>,
    #               <url>, <module-name> - this value may undergo translation
    #               to eventually evaluate to a filesystem reference
    #   tarball  =  always located in SOURCES.  Proc-Daemon-1.0.tgz
    #   name     =  Proc-Daemon
    #   module   =  Proc::Daemon
    #   evaldir  =  directory where tarball is extracted
    #   tardir   =  the directory name inside the tarball

    %info = (%info, %opts);

    #   handle temporary files

    if ($TMPDIR = $info{tempdir}) {
        mkdir $TMPDIR, 0755 unless -d $TMPDIR;
        }
    else {
        my $msg = "Cannot run without File::Temp, please install ";
        $msg .= "or use the --tempdir option.";
        eval "use File::Temp qw/tempdir tempfile/";
        die "$@\n$msg\n" if $@;

        $Temp = 1;
        $info{dist} ||= "";
        $TMPDIR = tempdir(
            CLEANUP => $info{"no-clean"} || -d $info{dist} ? 0 : 1
            );
        };

    #   set up local account to build packages

    if ($info{"mk-rpm-dirs"}) {
        local $_ = "$ENV{HOME}/.rpmmacros";
        my $topdir = `echo -n $info{"mk-rpm-dirs"}`;
        if (!-e) {
            writefile($_, qq/%_topdir $topdir\n/);
            }
        elsif (-r) {
            my $s = readfile();
            writefile($_, qq/\n%_topdir $topdir\n/, ">>")
                unless $s =~ /topdir/is;
            }

        my @subdirs = qw|
            BUILD SOURCES SPECS SRPMS
            RPMS RPMS/i386 RPMS/i686 RPMS/noarch
            |;
        push @subdirs, "RPMS/$info{buildarch}" if $info{buildarch};
        for (map "$topdir/$_", "", @subdirs) {
            next if -e;
            mkdir($_, 0755) || die "Cannot make $_: $!";
            }

        print "RPM user environment set up.  Your system should be ";
        print "ready for packaging!\n";
        exit(0);
        }

    upgrade() if defined $info{upgrade};

    $info{dist} = shift @ARGV
        || syntax(\%desc, "No distribution specified!");

    #   deal with newer versions
    chkupgrade();

    $RPMDIR{BUILD} = getrpm_macdef("_builddir");
    $RPMDIR{SOURCES} = getrpm_macdef("_sourcedir");
    $RPMDIR{RPMS} = getrpm_macdef("_rpmdir");
    $RPMDIR{SRPMS} = getrpm_macdef("_srcrpmdir");
    $RPMDIR{SPECS} = getrpm_macdef("_specdir");
    $RPMDIR{ARCH} = getrpm_macdef("_arch");

    $info{buildarch} ||= $RPMDIR{ARCH};

    # check directory permissions

    my $dirserr = 0;
    my @dirs = ($RPMDIR{SRPMS}, $RPMDIR{SPECS}, $RPMDIR{BUILD});
    for (@dirs) {
        next if /%/; # e.g. %_specdir = "%{name}-%{version}"
        $dirserr++ unless -d && -w;
        }

    if ($dirserr) {
        print "RPM user environment - Your account does not have permissions ";
        print "to the requisite RPM directory structure.  cpan2rpm provides ";
        print "a simple mechanism for setting up your environment for ";
        print "non-root package building.  For more information, please refer ";
        print "to the --mk-rpm-dirs option in the man page\n";
        exit(1);
        }

    # set requirements patch override

    $ENV{CPAN2RPM_REQ_ALL} = $info{"req-scan-all"} || "";

    if ($< && $info{install}) {
        print "NON ROOT install requires sudo rpm privileges\n";
        if (system("sudo rpm -v > /dev/null")) {
            my $msg = "sudo failed, cannot use --install option!  You can\n";
            $msg .= "configure sudo with the following command:\n\n";
            $msg .= "  echo \"".getlogin()." ALL=/bin/rpm\" >> /etc/sudoers";
            die "\n$msg\n\nStopped";
            }

        print "sudo precheck successful\n";
        }
    }

sub get_mod {
    my $dist; $info{dist} = $dist if $dist = searchcpan();

    #
    #    a url was passed
    #

    if (isurl($info{dist})) {
        $info{tarball} = write_url($RPMDIR{SOURCES}, $info{dist});
        push @{$info{source}}, $info{dist};
        }

    #
    #    argument passed is a local file name
    #

    elsif (istarball($info{dist}, 1)) {
        cp($info{dist}, $RPMDIR{SOURCES})
            || die "get_mod(): cp [$info{dist}] - $!"
            ;
        ($info{tarball} = $info{dist}) =~ s|.*/||;
        }

    #
    #   argument passed is a directory
    #

    elsif (-d $info{dist}) {
        $info{dist} = $CWD if $info{dist} eq ".";
        }

    #
    #    assume argument passed is a Perl module name
    #

    else {
        $info{tarball} = get_cpan();
        }

    #    extract tarball

    unless (-d ($info{evaldir} = $info{dist})) {
        my $f = "$RPMDIR{SOURCES}/$info{tarball}";
        print "Tarball extraction: [$f]\n";
        $info{evaldir} = untar($f);
        }
    }

sub get_meta {
    print "Metadata retrieval\n";

    chdir $info{evaldir} || die "get_meta(): $!";

    local $_ = "$info{evaldir}/Makefile.PL";
    die qq/No "Makefile.PL" in tarball/ unless -e;
    die qq/Cannot read "Makefile.PL"/ unless -r;

    #   we want to protect us from exit()ing but without modifying the
    #   actual Makefile.PL since we may be operating in a directory

    my $PL = readfile();
    $PL =~ s/\bexit\b/return/gs;
    my ($x, $t) = $Temp ? tempfile() : (undef, "$TMPDIR/Makefile.$$");
    writefile($t, $PL);

    #   now we get the arguments passed to WriteMakefile

    {
    local $^W = 0;
    # grab parameters to WriteMakefile()
    *ExtUtils::MakeMaker::WriteMakefile = sub {%meta = @_};
    local @ARGV = ();
    push @ARGV, $info{"make-maker"} if $info{"make-maker"};
    # no input or output
    std_close();
    # execute the makefile
    do $t;
    # clean up
    std_restore();
    unlink $t || die "get_meta(): rm[$t] - $!";
    }

    #   make sure dependencies are installed

    my @deps;
    my $deps = $meta{PREREQ_PM};
    for (keys %$deps) {
        $@ = ""; eval "use $_ $deps->{$_}";
        push @deps, "$_ >= $deps->{$_}" if $@; 
        }
    my $msg = "Unable to build module, the following dependencies have failed:";
    die "$msg\n  " . join("\n  ", @deps) . "\nStopped" if @deps;

    #   figure out package name

    $info{module} ||= $meta{DISTNAME} || $meta{NAME};
    if (!$info{module}) {
        #   for directories, guess at the tarball name
        if (-d $info{dist}) {
            ($info{tarball} = $info{dist}) =~ s|.*/||;
            # a source directory may include a version #
            $info{tarver} = $info{tarball} =~ s/-(\d+\.?\d*)$// ? $1 : "";
            }
        $info{module} = $info{tarball};
        $info{module} =~ s/-(\d+\.?\d*)$tarRE$//i;
        $info{module} =~ s/-/::/g;
        }

    ($info{name} = $info{module}) =~ s/::/-/g;
    $info{tarball} = $info{name} if -d $info{dist};

    die "No package name available.  Stopped"
        unless $info{name};

    $info{spec} ||= "$RPMDIR{SPECS}/$info{name}.spec";

    #   get module description info

    my $from = $meta{ABSTRACT_FROM} || $meta{VERSION_FROM};
    ($from = "$info{module}.pm") =~ s/.*:// unless $from;
    $from = readfile($from);

    if (!$meta{ABSTRACT} && $from) {
        local $_ = $from;
        ($meta{ABSTRACT}) = /=head\d\s+NAME.*?-\s*(.*?)$/ism;
        $meta{ABSTRACT} ||= "";
        ($meta{DESCRIPTION}) = /=head\d\s+SYNOPSIS\s+(.*?)=head/ism;
        $meta{DESCRIPTION} ||= "";
        $meta{DESCRIPTION} =~ s/E<lt>/</ig;
        $meta{DESCRIPTION} =~ s/E<gt>/>/ig;
        }

    $info{author} ||= $meta{AUTHOR};

    if (!$info{author} && $from =~ /=head\d\s+AUTHORS?\s+(.*?)=/is) {
        local $_ = $1;
        my ($em) = /(\S+(@|\sat\s)\S+)/is;
        $em ||= "";
        $em =~ s/\.$//;             # e.g. Erick Calder e@arix.com.
        ($_) = /((?:\S+\s+){1,3})\Q$em\E/is;
        $_ ||= "";
        s/[^a-zA-Z ]+//g;           # Peter Behroozi, behroozi@www.pls.uni.edu
        trim(); s/\s+/ /g;
        $em =~ s/\s+at\s+/@/g;
        $em =~ s/[()<>]//g;           # Eryq (eryq@zeegee.com)
        $_ .= " <$em>";
        s/E<(lt|gt)>//ig;           # Erick Calder E<lt>e@arix.comE<gt>
        $info{author} = $_;
        }

    if (!$info{author}) {
        # Extract generic author from any of the urls
        for (@{$info{source}}) {
            if (isurl() && m%author.*/([A-Z\-]+)/[^/]+$%) {
                $info{author} = (lc $1).'@cpan.org';
                last;
                }
            }
        }

    die "No author information found, please use --author option.  Stopped"
        unless $info{author};

    #   extract version

    $info{version} ||= $meta{VERSION};
    unless ($info{version}) {
        $info{version} = ExtUtils::MM_Unix->parse_version($from)
            if $from = $meta{VERSION_FROM};
        trim($info{version}); # parse_version() returns spaces
        }
    $info{version} ||= $info{tarver};

    die "No version found, please use --version option.  Stopped"
        unless $info{version};

    ($info{tardir} = $info{evaldir}) =~ s|.*/||;

    #   for directories, guess some of the needed values

    if (-d $info{dist}) {
        ($info{tardir} = $info{module}) =~ s|::|-|g;
        $info{tardir} .= "-$info{version}"
            unless $info{tardir} =~ /-(\d+.*)$/;
        $info{tarball} = "$info{tardir}.tar.gz";
        }

    #   tarballs without a subdir need one created

    $info{create} = $info{tardir} =~ s/\+$// ? "-c" : "";

    #    create file-list for spec's %doc section

    my %doc;
    for (split $/, readfile("MANIFEST")) {
        s|[/\s].*||;
        # get subdirs (with some exceptions)
        $doc{$_} = 1, next if -d && !/^(t|lib)$/;
        # list all files that match the regexp
        $doc{$_} = 1 if /$docRE/i;
        }
    $info{doc} ||= "";
    $info{doc} = join " ", $info{doc}, keys %doc
        unless $info{doc} =~ /^=/;
    if ($info{doc}) {
        $info{fixin} = <<EOF;
            grep -rsl '^#!.*perl' $info{doc} |
            grep -v '\.bak\$' |xargs --no-run-if-empty \\
            %__perl -MExtUtils::MakeMaker -e 'MY->fixin(\@ARGV)'
EOF
        }
    $info{doc} &&= "%doc $info{doc}";

    #    assemble other info

    $info{summary} = "$info{name} - " . ($meta{ABSTRACT} || "Perl module");
    $info{description} = $meta{DESCRIPTION} if $meta{DESCRIPTION};
    push @{$info{source}}, $info{tarball}
        unless $info{source};
    $info{changelog} = changelog();

    $info{"find-provides"}
        &&= qq/%define __find_provides $info{"find-provides"}/;
    $info{"find-requires"}
        &&= qq/%define __find_requires $info{"find-requires"}/;

    #   option lists

    $info{"opts-simple"} = [qw/
        name summary version release epoch
        vendor packager distribution license group url
        buildroot buildarch
        /];

    $info{"opts-agg"} = [qw/
        provides requires buildrequires source patch
        /];

    $info{"opts-secs"} = [qw/
        prep build install clean changelog tag files
        /];

    #   handle aggregate options

    $info{"$_-list"} = optagg() for @{$info{"opts-agg"}};

    #   section handlers

    my $prologue = $info{prologue};
    for (@$prologue) {
        my ($sec, $v) = /^(\w+):(.*)$/ || next;
        $info{prologue}{$sec} = $v . $/;
        }

    my $epilogue = $info{epilogue};
    for (@$epilogue) {
        my ($sec, $v) = /^(\w+):(.*)$/ || next;
        $info{epilogue}{$sec} = $v . $/;
        }

    for (@{$info{"opts-secs"}}) {
        $info{prologue}{$_} ||= "";
        $info{epilogue}{$_} ||= "";
        }

    #   special situations

    if ($info{"no-requires"}) {
        my $noreqs = "";
        $noreqs .= qq/-e '$_' / for split /\s*,\s*/, $info{"no-requires"};
        delete $info{"no-requires"};
        $info{"no-requires"}{"define"}
            = "%define custom_find_req %{_tmppath}/%{NVR}-find-requires";
        $info{"find-requires"} = "%define __find_requires %{custom_find_req}";
        local $_ = qq[cat <<EOF > %{custom_find_req}
            #!/bin/sh
            /usr/lib/rpm/find-requires |grep -v $noreqs
            EOF
            chmod 755 %{custom_find_req}
            ];
        s/^\s+//mg;
        $info{"no-requires"}{"install"} = $_;
        $info{"no-requires"}{"clean"} = "rm -f %{custom_find_req}";
        }

    $info{"no-requires"}{"define"} ||= "";
    $info{"no-requires"}{"install"} ||= "";
    $info{"no-requires"}{"clean"} ||= "";

    # fix patch info

    my $i = 0;
    $info{"patch-files"} = "";
    $info{"patch-apply"} = "";

    for (split $/, $info{"patch-list"}) {
        s/.*:\s+//;
        $info{"patch-files"} .= "Patch$i: $_\n";
        $info{"patch-apply"} .= "%patch$i -p1\n";
        # put patches in RPM dir if needed
        cp($_, $RPMDIR{SOURCES})
            || die "Unable to copy patch [$_]: $!";
        }

    # return to user's directory

    chdir $CWD;
    }

#
#    generate s spec file
#

sub mk_spec {
    print "Generating spec file\n";

    # clean warnings about missing keys

    $info{$_} ||= "" for keys(%info), @{$info{"opts-simple"}};
    $info{$_} ||= "" for qw/make fixin/;    # extra tags
    $info{"$_-list"} ||= "" for @{$info{"opts-agg"}};

    # strip ctrl-M's from Windoze files

    $info{$_} =~ s/\r//g for keys %info;

    # generalise whenever possible

    for (qw/tardir source/) {
        $info{$_} =~ s/$info{name}/%{pkgname}/;
        $info{$_} =~ s/$info{version}/%{version}/;
        }

    $info{description} =~ s/\s+$//;
    $info{maketest} = $info{"make-no-test"}?0:1;
    $info{vendor} = $info{author};

    if ($info{name} eq "ExtUtils-MakeMaker") {
        # MakeMaker builds itself using itself
        $ENV{PERL5LIB} = $ENV{PERL5LIB}?"lib:$ENV{PERL5LIB}":"lib";
        }

    # Versions between 5.91 and 6.05 need PREFIX= on Makefile.PL line

    my $perl = q/`%%{__perl} -MExtUtils::MakeMaker -e '%s'`/;
    my $mm_maker = q#
        print qq|PREFIX=%{buildroot}%{_prefix}|
            if \\$ExtUtils::MakeMaker::VERSION =~ /5\.9[1-6]|6\.0[0-5]/
        #;
    $mm_maker =~ s/\s+/ /gs;
    $info{"make-maker"} ||= sprintf($perl, $mm_maker);

    # Versions before 5.91 need PREFIX= on install line
    # Versions after 6.05 need DESTDIR= on install line

    my $mm_install = q#
        print \\$ExtUtils::MakeMaker::VERSION <= 6.05
            ? qq|PREFIX=%{buildroot}%{_prefix}|
            : qq|DESTDIR=%{buildroot}|
        #;
    $mm_install =~ s/\s+/ /gs;
    $info{"make-install"} ||= sprintf($perl, $mm_install);

    if ($info{"shadow-pure"}) {
        # Force pure perl installs into first @INC slot
        $info{"make-maker"} .= sprintf("; %%{__perl} -pi -e '%s' Makefile",
            q|s/(INSTALL[PVS]\w+LIB =).*/$1 \$(INSTALLARCHLIB)/|
            );

        # Avoid man page conflicts with default
        $info{"make-maker"} .= sprintf("; %%{__perl} -pi -e '%s' Makefile",
            q|s,(INSTALLMAN3DIR =[^/]+)/.*,$1/man/man3,|
            );
        }

    # prepend string to separate module from usual namespace

    my $pkgname = $info{name};
    $info{name} = "perl-" . $info{name} unless $info{"no-prfx"};

    my $spec = <<ZZ;
        #
        # This spec file was automatically generated by cpan2rpm v$VERSION
        # For more information please visit: http://perl.arix.com/
        #

        %define pkgname $pkgname
        %define filelist %{pkgname}-%{version}-filelist
        %define NVR %{pkgname}-%{version}-%{release}
        %define maketest $info{maketest}
ZZ

    $spec .= $info{"no-requires"}{"define"} . $/;
    $spec .= $info{"find-provides"} . $/;
    $spec .= $info{"find-requires"} . $/;

    #   add simple tags

    for (@{$info{"opts-simple"}}) {
        $spec .= "$_:\t$info{$_}\n" if $info{$_};
        }

    #   add lists

    $spec .= $info{"provides-list"};
    $spec .= $info{"requires-list"};
    $spec .= $info{"buildrequires-list"};
    $spec .= $info{"source-list"};
    $spec .= $info{"patch-files"};
    $spec .= $info{epilogue}{tag};

    $spec .= q/%description/ . "\n$info{description}\n";

    $spec .= <<ZZ;
        #
        # This package was automatically generated with the cpan2rpm
        # utility.  To get this software or for more information
        # please visit: http://perl.arix.com/
        #
ZZ

    #   handle sections

    $spec .= q/%prep/ . $/;
    $spec .= $info{prologue}{prep};
    $spec .= <<ZZ;
        %setup -q -n $info{tardir} $info{create}
        $info{"patch-apply"}
        chmod -R u+w %{_builddir}/$info{tardir}
ZZ
    $spec .= $info{epilogue}{prep};

    $spec .= q/%build/ . $/;
    $spec .= $info{prologue}{build};
    $spec .= <<ZZ;
        CFLAGS="\$RPM_OPT_FLAGS"
        %{__perl} Makefile.PL $info{"make-maker"}
        %{__make} $info{"make"}
        %if %maketest
            %{__make} test
        %endif
ZZ
    $spec .= $info{epilogue}{build};

    $spec .= q/%install/ . $/;
    $spec .= $info{prologue}{install};
    $spec .= <<ZZ;
        [ "%{buildroot}" != "/" ] && rm -rf %{buildroot}
        $info{"no-requires"}{"install"}

        %{makeinstall} $info{"make-install"}

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

        # SuSE Linux
        if [ -e /etc/SuSE-release ]; then
            %{__mkdir_p} %{buildroot}/var/adm/perl-modules
            %{__cat} `find %{buildroot} -name "perllocal.pod"`  \\
                | %{__sed} -e s+%{buildroot}++g                 \\
                > %{buildroot}/var/adm/perl-modules/%{name}
        fi

        # remove special files
        find %{buildroot} -name "perllocal.pod" \\
            -o -name ".packlist"                \\
            -o -name "*.bs"                     \\
            |xargs -i rm -f {}

        # no empty directories
        find %{buildroot}%{_prefix}             \\
            -type d -depth                      \\
            -exec rmdir {} \\; 2>/dev/null

        %{__perl} -MFile::Find -le '
            find({ wanted => \\&wanted, no_chdir => 1}, "%{buildroot}");
            print "%defattr(-,root,root)";
            print "$info{doc}";
            for my \$x (sort \@dirs, \@files) {
                push \@ret, \$x unless indirs(\$x);
                }
            print join "\\n", sort \@ret;

            sub wanted {
                return if /auto\$/;

                local \$_ = \$File::Find::name;
                my \$f = \$_; s|^%{buildroot}||;
                return unless length;
                return \$files[\@files] = \$_ if -f \$f;

                \$d = \$_;
                /\\Q\$d\\E/ && return for reverse sort \@INC;
                \$d =~ /\\Q\$_\\E/ && return
                    for qw|/etc %_prefix/man %_prefix/bin %_prefix/share|;

                \$dirs[\@dirs] = \$_;
                }

            sub indirs {
                my \$x = shift;
                \$x =~ /^\\Q\$_\\E\\// && \$x ne \$_ && return 1 for \@dirs;
                }
            ' > %filelist

        [ -z %filelist ] && {
            echo "ERROR: empty %files listing"
            exit -1
            }
ZZ
    $spec .= $info{epilogue}{install};
    $spec .= $info{fixin};

    $spec .= q/%clean/ . $/;
    $spec .= $info{prologue}{clean};
    $spec .= <<ZZ;
        [ "%{buildroot}" != "/" ] && rm -rf %{buildroot}
        $info{"no-requires"}{"clean"}
ZZ
    $spec .= $info{epilogue}{clean};

    $spec .= q/%files -f %filelist/ . $/;
    $spec .= $info{epilogue}{files};

    $spec .= q/%changelog/ . $/;
    $spec .= $info{prologue}{changelog};
    $spec .= <<ZZ;
        * $info{changelog}
        - Initial build.
ZZ
    $spec .= $info{epilogue}{changelog};

    ($_ = $spec) =~ s/^\s+//gm;    # clean up

    writefile($info{spec});
    exit if $info{"spec-only"};
    }

#
#    build the package
#

sub mk_rpm {
    if (-d $info{dist}) {
        system("perl Makefile.PL && make") == 0 || die "mk_rpm(): $!"
            unless ($info{name} eq "cpan2rpm");
        system("make dist") == 0 || die "mk_rpm('make dist'): $!";

        cp($info{tarball}, $RPMDIR{SOURCES})
            || die "mk_rpm(): cp [$info{tarball}] - $!"
            ;
        }

    $info{rpm} = sprintf("%s/%s-%s-%s.%s.rpm"
        , "$RPMDIR{RPMS}/$info{buildarch}"
        , $info{name}
        , $info{version}
        , $info{release}
        , $info{buildarch}
        );

    return if -r $info{rpm} && !$info{force};

    my $ret = 0;
    print "Generating package\n";

    system($RPM, "-bp",  $info{spec});
    warn("RPM test unpacking failed!") if $ret = $? >> 8;

    if ($ret == 0) {
        my @cmd = ($RPM, '-ba', '--clean', $info{spec});
        splice @cmd, 2, 1 if $info{"no-clean"};
        print join " ", ">>", @cmd, "\n" if defined $info{debug};
        system(@cmd);
        die "RPM build failed!" if $ret = $? >> 8;
        }

    return $ret;
    }

#
#    if requested, will also install the resulting RPM
#

sub inst_rpm {
    my $rpm = shift || $info{rpm};
    return unless $info{install};

    print "Installing package\n";
    my @cmd = (qw/rpm -Uvh/, $rpm);
    unshift @cmd, "sudo" if $<;
    system(@cmd);
    return $? >> 8;
    }

# --- module retrieval functions ----------------------------------------------

#
#    Walks search.cpan.org for the latest uploaded distribution.
#    Uses LWP instead of CPAN to determine the tarball.
#

sub searchcpan {
    my $dist = shift || $info{dist};

    # Abort unless it smells like a CPAN module
    return unless $dist =~ /^[\w:\-.]+$/;

    my $cache = "$RPMDIR{SOURCES}/$dist";
    if (!$info{force} and my $url = readlink($cache)) {
        print "Using cached URL\n";
        return $url;
        }

    print "Searching CPAN website\n";

    my $base = "http://search.cpan.org";
    my $url = "$base/dist/$dist"; $url =~ s/::/-/g;

    # XXX - this algorithm may change as the
    # search.cpan.org web site output changes.

    local $_ = http_get($url) || return;
    m% \<a[^<>]*         # Begin Anchor tag
        href\s*=\s*       # href parameter
        (['"]?)           # Maybe quote
        ([^<>\s"']*)      # Extract link as $2
        \1                # Maybe quote
        [^<>]*\>          # End Anchor tag
        \s*Download       # of the "Download" link
        %ix;              # case insensitive HTML

    print("- $info{dist} not found!\n"), return
        unless $2;

    print "Found: $url\n";
    $url = "$base/$2";
    symlink($url, $cache);
    return $url;
    }

#
#    grabs the module from CPAN and places in the SOURCES directory
#    ACHTUNG: at present, only the latest version of the module
#    can be retrieved.  For building earlier versions, retrieve the
#    tarball manually.
#

sub get_cpan {
    my $module = shift || $info{dist};

    print "Retrieving module from CPAN\n";
    require  CPAN;
    import   CPAN 0.59;

    my $m = CPAN::Shell->expand("Module", $module)
        || die "Module not found on CPAN!";

    # somewhere between CPAN version 1.52 and 1.65 the interface
    # changed, moving all relevant data to the RO key

    $m = $m->{RO} if $m->{RO};

    my $a = CPAN::Shell->expand("Author", $m->{CPAN_USERID});
    $a = $a->{RO} if $a->{RO};
    $info{author} ||= "$a->{FULLNAME} <$a->{EMAIL}>";

    my $f = $m->{CPAN_FILE};
    push @{$info{source}}, sprintf("%s/authors/id/%s"
        , "http://www.cpan.org"
        , $f
        );

    my $tarball = $f; $tarball =~ s|.*/||;

    # bail if tarball already there (unless we're being --force'd)
    return $tarball if -s "$RPMDIR{SOURCES}/$tarball"
        && -r _
        && ! defined $info{force}
        ;

    get($f);

    $CPAN::Config->{'keep_source_where'} ||= "UNKNOWN";
    my $ff = sprintf("%s/authors/id/%s"
        , $CPAN::Config->{'keep_source_where'}
        , $f
        );

    system("cp", $ff, $RPMDIR{SOURCES}) if -r $ff;
    $ff =~ s|.*/||;
    $ff;
    }

# --- tar handling functions --------------------------------------------------

#
#    determines whether given filename represents a tarball
#    optionally dies it file doesn't exist or is not readable
#

sub istarball {
    my ($fn, $fschk) = @_;
    my $is = $fn =~ /$tarRE/i;
    return $is unless $fschk && $is;
    -r $fn || die "tarball: $!";
    }

sub ls {
    my $d = shift || $_;
    opendir(DIR, $d) || die "ls(): $!";
    my @f = grep { !/^\.\.?$/ } readdir(DIR);
    closedir(DIR);
    ($d, @f);
    }

sub lsd {
    my $d = shift || $_;
    opendir(DIR, $d) || die "lsd(): $!";
    my @d = grep { !/^\.\.?$/ && -d "$d/$_" } readdir(DIR);
    closedir(DIR);
    "$d/$d[0]";
    }

#
#    extracts a tarball
#

sub untar($) {
    local $_ = shift;
    my $dst = shift || $TMPDIR;

    my @cmd = (qw/tar -xz --directory/, $dst, "-f", $_);
    @cmd = (qw/tar -xj --directory/, $dst, "-f", $_) if /\.tar\.bz2$/i;
    @cmd = (qw/unzip -d/, $dst, $_) if /\.zip$/i;
    system @cmd;
    system("chmod", "-R", "u+w", $dst);
    lsd($dst);
    }

# --- file handling functions -------------------------------------------------

#
#    returns the contents of a given file or undef if the
#    file does not exist
#

sub readfile {
    local $_ = shift || $_;
    return undef unless -r;

    local $/ = undef;
    open(_) || die "$! [$_].  Stopped ";
    $_ = <_>;
    close(_);
    $_;
    }

#
#    writes a file, from a string
#

sub writefile($@) {
    my $fn = shift;
    local $_ = shift || $_;
    my $op = shift || ">";

    open (FILE, "$op $fn") || die "writefile('$fn'): $!. Stopped";
    binmode(FILE);
    print FILE;
    close(FILE);
    $fn;
    }

sub cp {
    my ($f, $d, $ff) = @_;
    $f =~ s/~/$ENV{HOME}/;
    return 1 unless -r $f;
    ($ff = $f) =~ s|.*/||;
    return 1 if finode($f) eq finode("$d/$ff");
    system("cp", "-u", $f, $d) == 0;
    }

#    0: dev, 1: inode, the combination guarantees
#    a unique file in a filesystem

sub finode {
    local $_ = shift || $_;
    my @i; "$i[0]$i[1]" if @i = stat;
    }

#    simple test to determine if it's a URL

sub isurl {
    local $_ = shift || $_;
    scalar m#(ht|f)tp://#;
    }

#    Syntax: content = http_get [url]

sub http_get {
    my $url = shift || $_;

    $HTTPWARN = 1 if $info{dist} =~ /libwww-perl/;

    if ($@ = "", eval "use HTTP::Request::Common; use LWP::UserAgent;", !$@) {
        my $ua = LWP::UserAgent->new();
        return $ua->request(GET($url))->content || "";
        }
    elsif ($HTTPWARN == 0) {
        print "\nWARNING: libwww-perl module not found.  To install, one ";
        print "of the following options may help:\n\n";

        local $\ = $/;
        my $url = "http://www.rpmfind.net/linux/rpm2html/search.php";
        $url .= "?query=perl-libwww-perl";
        print "  1) Try $url";
        $url = "http://www.cpan.org/modules/by-module/LWP/";
        $url .= "libwww-perl-5.68.tar.gz";
        print "  2) Specify the full URL of the tarball manually.";
        print "     cpan2rpm -i $url";
        print "  3) Download tarball and specify file on commandline.";
        print "  4) Configure CPAN: perl -MCPAN -eshell";
        print "  5) cpan2rpm -i libwww-perl\n";
        print "Trying HTTP::Lite...";
        }

    if ($@ = "", eval "use HTTP::Lite;", !$@) {
        my $http = HTTP::Lite->new();
        $http->request($url) || die "http_get(): $!.  Stopped";
        return $http->body() || "";
        }
    elsif ($HTTPWARN == 0) {
        print "\nWARNING: this alternative module could not be found ";
        print "either!  Please install the libwww-perl package ";
        print "as indicated above.\n\n";
        print "Trying external programs...\n";
        }

    $HTTPWARN = 1;

    my @prg = (
        "/usr/bin/lynx -source $url",
        "/usr/bin/links -source $url",
        "/usr/bin/wget -O - $url",
        "/usr/bin/ncftpget $url && cat " . ($url =~ m|.*/(.*)|),
        );

    for (@prg) {
        my ($p) = /^(\S+)/;
        next unless -e $p;
        my $ret = qx/$_/;
        print("Retrieving with [", $p =~ m|([^/]+)$|, "]\n"), return $ret
            if $? == 0;
        }

    my $msg = "External program support failed.  Manual download required";
    die "> $msg.\nStopped";
    }

#    Syntax: tarball = write_url <directory> [url]

sub write_url {
    my ($d, $url) = @_;
    $d =~ s|/$||;    # no trailing /s

    $url ||= $_;
    return unless $url;

    my $tar; ($tar = $url) =~ s|.*/||;
    return $tar if -s "$d/$tar" && -r _ && !$info{force};

    print "Retrieving URL\n";
    local $_ = http_get($url);
    return unless $_;

    writefile("$d/$tar");
    return $tar;
    }

sub std_close {
    open(OLDOUT, ">&STDOUT")   || die "std_save(): $!";
    open(OLDERR, ">&STDERR")   || die "std_save(): $!";
    open(OLDIN,  "<&STDIN")    || die "std_save(): $!";
    open(STDOUT, ">/dev/null") || die "std_close(): $!";
    open(STDERR, ">/dev/null") || die "std_close(): $!";
    open(STDIN,  "</dev/null") || die "std_close(): $!";
    }

sub std_restore {
    open(STDOUT, ">&OLDOUT") || die "std_restore(): $!";
    open(STDERR, ">&OLDERR") || die "std_restore(): $!";
    open(STDIN,  "<&OLDIN")  || die "std_restore(): $!";
    }

# --- miscellany --------------------------------------------------------------

sub optagg {
    my $nm = shift || $_;
    my @opt; push @opt, split /,/ for @{$info{$nm}};
    my $ret = "";
    $ret .= /^%/ ? "$_\n" : "$nm: $_\n" for @opt;
    $ret;
    }

sub getrpm_macdef($) {
    my $key = shift;
    chomp(local $_ = qx/rpm --eval \%{$key}/);
    s/^\s+//; s/\s*\n+/ /gs;
    $_;
    }

sub inpath($) {
    my $cmd = shift;
    -x "$_/$cmd" && return "$_/$cmd" for split /:/, $ENV{PATH};
    }

sub chkupgrade {
    return if defined $info{"no-upgrade-chk"};
    print "Upgrade check\n";

    my $up = "";
    eval {
        alarm(5);
        $SIG{ALRM} = sub {
            die "Network too slow, check elapsed...\n";
            };
        my $mod = $info{dist}; $mod =~ s|.*/||;
        local $_ = "http://perl.arix.com/cpan2rpm/?";
        $_ .= "version=$VERSION&mod=$mod";
        $up = http_get();
        };
    alarm(0);
    return unless $up eq "Y";

    local $\ = $/;
    print "";
    print "* A newer version of this program is now available. To upgrade";
    print "* enter the following command: $0 --upgrade\n";
    }

sub upgrade {
    $info{install}++;
    my $url = http_get("http://perl.arix.com/cpan2rpm/?latest=gz");
    unless (write_url($TMPDIR, $url)) {
        local $\ = $/;
        print "\nERROR: Unable to automatically upgrade, please visit our web";
        print "site at: http://perl.arix.com, download the latest tarball and";
        print "refer to the installation instructions in the README file.\n";
        exit(-1);
        }

    my ($f) = $url =~ m|.*/(.*)|;
    my @ret = qx|$RPM -ta $TMPDIR/$f|;
    die "upgrade(): $!" if $?;
    /Wrote:\s+(.*)$/ && ($f = $1) && last for reverse @ret;
    inst_rpm($f);
    exit;
    }

sub changelog {
    my @dow = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
    my @mon = ("Jan", "Feb", "Mar", "Apr", "May", "Jun"
        , "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
        );

    return sprintf("%s %s %d %d %s"
          , $dow[(localtime)[6]]
        , $mon[(localtime)[4]]
        , (localtime)[3]
        , 1900 + (localtime)[5]
        , sprintf("%s\@%s", (getpwuid($<))[0], hostname())
        );
    }

sub trim {
    map { $_ ||= ""; s/^\s+//; s/\s+$//; } @_;
    unless (defined wantarray()) {
        $_ ||= ""; s/^\s+//; s/\s+$//;
        }
    $_[0] if @_ == 1;
    }

sub syntax {
    my $args = shift;
    my $warn = shift;

    print "Error:\t$warn\n\n" if $warn;

    local $_ = <<EOF;
    This script automates the creation of RPMs from CPAN modules.
    For further information please see the man page.
EOF
    s/^\s+//mg; print;
    print "\nSyntax: cpan2rpm [options] <module>\n\n";
    print "Where <module> is either the name of a Perl module (e.g.\n";
    print "Proc::Daemon) or of a tarball (e.g. Proc-Daemon-0.02.tar.gz),\n";
    print "and [options] is any of the following:\n\n";
    for (sort keys %$args) {
        my ($arg) = split /[:=|]/;
        $arg = "-$arg" if length($arg) > 1;
        $arg = "-$arg" if $arg;
        printf("  %-15s %s\n", $arg, $args->{$_});
        }
    print "\n";
    exit(1);
    }

1;    # yipiness

__END__

=head1 NAME

cpan2rpm - A Perl module packager

=head1 SYNOPSIS

This script generates an RPM package from a Perl module.  It uses the standard RPM file structure and creates a spec file, a source RPM, and a binary, leaving these in their respective directories.

The script can operate on local files, directories, urls and CPAN module names.  Install this package if you want to create RPMs out of Perl modules.

=head1 DESCRIPTION

cpan2rpm [options] <distribution>

The syntax for cpan2rpm requires a single I<distribution> name, which can take one of four different forms:

=over

=item B<1) a CPAN module name> (e.g. XML::Simple) - When a module name is passed, the script will "walk" search.cpan.org to determine the latest distribution.  If an exact match is not found, the CPAN module is used to make this determination.  If you have not yet configured this module, please refer to the REQUIREMENTS section below for further instructions.

=item B<2) a URL> (both F<http://> and F<ftp://> style locators will work) - In this and the above case, an automatic download of the needed tarball is performed (see notes for how).  The tarball is deposited in the SOURCES directory.

=item B<3) a path to a tarball> (e.g. F</tmp/XML-Simple-1.05.tar.gz>) - In this case, the tarball indicated gets copied to the SOURCES directory.

=item B<4) a directory path> - The directory specified must contain a F<Makefile.PL>.  If the user intends to build a package from a directory (i.e. user does NOT specify B<--spec-only>), the commands:

=back

    perl Makefile.PL
    make
    make dist

will be performed in that directory in order to create the tarball necessary for package creation.

=head1 NOTES

At present the script will handle B<.tar.gz>, B<.tgz>, B<.bz2> and B<.zip> tarballs but each of these types requires the appropriate decompression programs installed on the system.

Spec files generated will generally assume header values as configured in the RPM macro files which are evaluated in the following order: F</usr/lib/rpm/macros>, F</etc/rpm/macros> and F<~/.rpmmacros>.  Most of these headers can, however, be overridden through options.  Whenever a header is neither configured in the RPM macro files nor is passed at the command line, the script will seek to calculate a proper value and supplies a default as stated for each option below.  It is thus typically sufficient to provide only the I<distribution> name.

=head1 OPTIONS

The distribution name may be preceded by a number of optional arguments which modify the behaviour of the script.  These options are grouped into three main categories as follows:

=head2 SPEC Options

The following options control the contents of the specification file generated.  They come in four flavours as follows:

B<Simple Tags>

These represent all tags which get inserted in the package with single values.  The option may be used on the command line only once.

=over

=item B<--name=C<string-value>>

This option corresponds to the I<Name> tag in the spec file.  As is customary with Perl RPMs, the string C<perl-> will be prepended to any value passed here.  If no value is supplied, the script will use the NAME field found in the module's Makefile.PL

=item B<--no-prfx>

Even though this script is meant to build RPM packages from CPAN modules, it may be used on a more generic basis, thus the C<perl-> prefix in a package may be undesirable.  As an example, cpan2rpm generates itself but is not called C<perl-cpan2rpm>.  This option suppresses the aforementioned prefix in the package name.

=item B<--summary=C<string-value>>

A one-line description of the package.  If left unspecified the script will use the module name, appending an abstract whenever available.

=item B<--version=C<float-value>>

The script determines the version number of the module by consulting the F<Makefile.PL>'s VERSION or VERSION_FROM fields.  If neither is specified, it parses the tarball name.  Note: If you're looking to get the version of cpan2rpm itself, see the I<-V> option.

=item B<--release=C<integer-value>>

The package release number. Defaults to 1.

=item B<--epoch=C<integer-value>>

By default, this tag is not written to the spec file.  Enter a value here when needed.

=item B<--author=C<string-value>>

This is the name and address of the person who authored the module.  Typically it should be in the format: I<Name <e-mail-addressE<gt>>.  If left unspecified, the script will attempt to extract it from the tarball's MakeMaker file, failing to build the package otherwise.  There is no default for this option.

=item B<--packager=C<string-value>>

This is you (if you're packaging someone else's module).  The string should be in the same format as for --author and defaults to: C<Arix International <cpan2rpm@arix.comE<gt>> unless the RPM macro files provide a value.

=item B<--distribution=C<string-value>>

This key overrides the %{distribution} tag as defined in the macros files.  There is no default for this tag and will be left out unless specified.

=item B<--license=C<string-value>>

The license header specified in the spec file.  This field is also sometimes referred to as I<Copyright>, but I<License> is a more suitable name and has become more common.  Defaults to C<Artistic>, Perl's own license.

=item B<--group=C<string-value>>

This is the RPM group.  For further information on available groups please see your RPM documentation.  Defaults to C<Applications/CPAN>.

=item B<--url=C<string-value>>

The home url for the package.  Defaults to F<http://www.cpan.org>.

=item B<--buildarch=C<string-value>>

Allows specification of an architecture for building the RPM.  Currently defaults to the I<%_arch> macro from rpm.

=item B<--buildroot=C<string-value>>

Allows specifying a directory to use as a BuildRoot.  Don't mess with this is you don't know what it is.  Defaults to: C<%{_tmppath}/%{name}-%{version}>.

=item B<--description=C<string-value>>

This text describes the package/module.  This value is picked up from the POD's Synopsis section in the module.  Defaults to C<None.>.

=back

B<Aggregate Tags>

These represent tags which may be repeated in the spec file.  With all of the following, users may either specify a single option with a comma-delimited string of values, or multiple options, each with a single value.

I<exempli gratia>

--requires="rpm, rpm-build"
--requires="rpm" --requires="rpm-build"

=over

=item B<--provides=C<string-value>>

Indicates that a package is provided by the module being built.  RPM will generate an appropriate list of provide dependencies and any passed here will be I<in addition> to those calculated.

=item B<--requires=C<string-value>>

Indicates packages that should be required for installation.  This option works precisely as B<--provides> above.

=item B<--no-requires=C<string-value>>

Suppresses generation of a given required dependency.  Sometimes authors create dependencies on modules the packager can't find, sometimes RPM generates spurious dependencies.  This option allows the packager to arbitrarily supress a given requirement.

=item B<--buildrequires=C<string-value>>

This option indicates dependencies at build time.

=item B<--patch=C<string-value>>

Allows for specifying patch files to be inserted into the spec file and applied when building the source.

=item B<--doc=C<string-value>>

This option may be used to add values to the I<%doc> line in the spec's I<%files> section.  By default, cpan2rpm examines the contents of a tarball, using a regular expression to pick up files it recognises as belonging to the F</usr/share/doc> directory.  If your module contains files cpan2rpm does not recognise, they may be added with this option.

Additionally, the user may replace the calculated list by providing values prepended with an equal sign.  In the following example, ONLY the C<Changes> file is added to the list, dismissing any files found by the script:

I<--doc "=Changes">

=back

B<Section options>

These represent tags which may be repeated in the spec file.  Users may specify these either with a single option and a comma-delimited string of values, or by repeating the option, each with a single value.

=over

=item B<--prologue=C<E<lt>sectionE<gt>:E<lt>codeE<gt>>>

This option allows the user to insert arbitrary code at the top of a given section of the spec file.  The section is named in the value passed to the option as the first word followed by a colon.  At present, the following sections are supported: I<prep>, I<build>, I<install>, I<clean>, I<changelog>.

=item B<--epilogue=C<E<lt>sectionE<gt>:E<lt>codeE<gt>>>

As with the previous option, this may be used to insert code at the end of a given section.  This option also supports the I<tag> and I<files> sections which allow for the user to insert extra tags or files to the spec file.

I<exempli gratia>

--epilogue="tag:epoch 1"

=back

=head2 Building options

The following options control the package making process.

=over

=item B<--spec-only>

This option instructs the script to only generate a spec file and not build the RPM package.

=item B<--spec=path>

This option allows the user to specify the full-path of the spec file to produce.  By default, the specfile is placed in the SPECS directory and is named after the module with a F<.spec> extension.
Please note that cpan2rpm will overwrite existing files, so if you care about your current spec file, save it!

=item B<--make-maker=C<string-value>>

This option allows passing a string to the MakeMaker process (i.e. perl Makefile.PL <your-arguments-here>)

=item B<--make=C<string-value>>

Arguments supplied here get passed directly to the make process.

=item B<--make-no-test>

Use this option to suppress running a module's test suite during build.

=item B<--make-install=C<string-value>>

Allows user to supply arguments to the make install process.

=item B<--find-provides=C<string-value>>

=item B<--find-requires=C<string-value>>

These two options allow for redefining the RPM macros of the same name in the spec file.

=item B<--tempdir=C<string-value>>

Specify a temporary working directory instead of utilizing File::Temp.

=item B<--req-scan-all>

By default, the I<rpm-build> requirements script scans all files in a tarball for requirements information.  As this may on occasion generate requirements on the produced rpm that belong only to sample programs or other files not critical to the module being installed, we provide a patch the user may apply (included in this distribution as F<perl.req.patch>) which causes dependencies to be harvested from only F<.pm> files.  When this patch is installed, this switch reverses the behaviour, causing I<cpan2rpm> to scan all files as originally intended.

=item B<--no-clean>

By default, the system passes I<--clean> to F<rpmbuild>, thus removing the unpacked sources from the BUILD directory.  This option suppresses that functionality.

=item B<--shadow-pure>

Forces installation under F<installarchlib> even if the module is pure perl.  This is significant because it is first in the @INC search for module determination.  This will not do any good for modules with XS code or those that are already installed into an architecture dependent path.  This is most useful for those pure perl modules that come stock with the perl rpm itself (i.e. Test::Harness) but you wish to try another version without having to be forced to use "rpm --replacefiles" and destroying the old files.  Using this option will allow both versions of the module to be installed, but the new version will just mask the old version later in the @INC.  Additionally, the new man pages will mask the old man pages even though the man pages for both version will be installed.  This option should only be used as a last resort to install a module when "conflicts" errors occur on rpm installation such as the following: C<file from install of perl-Module-1.11-1 conflicts with file from package perl-5.x.x>
User may be required to use --force (see below) in conjuction with this option to build a fresh rpm before attempting to --install again.

=item B<--force>

By default the script will do as little work as possible i.e. if it has already previously retrieved a module from CPAN, it will not retrieve it again.  If it has already generated a spec file it will not generate it again.  This option allows the packager to force all actions, starting from scratch.

=item B<--install>

Install the RPM after building it.  If non-root user, you must have "sudo rpm" privileges to use this option.

=back

=head2 Miscellaneous options

The options below perform functions not closely related to the quotidien process of building a package.

=over

=item B<--mk-rpm-dirs=C<string-value>>

This option allows the non-root user to easily set up his account for building packages.  The option requires a directory path where the RPMS, SPECS, etc. subdirectories will be created.  These directories will contain the spec files, binaries and the source packages generated.  Additionally the I<%_topdir> macro will be defined in the F<~/.rpmmacros> file.  If this file doesn't exist it will be created, if it does but does not contain a definition for this macro, it will be appended to it.  Suggested value is F<~/redhat> but it's up to user.

Additionally, the script will create architecture directories F<i386>, F<i686> and F<noarch> and allows the user to pass B<--buildarch> to also create a directory for that architecture.

=item B<--upgrade>

Whenever a new version of this program becomes available, an automatic notification will be issued to the user of this fact.  The user may then choose to upgrade via this option.  The option takes no parameters.

=item B<--no-upgrade-chk|-U>

During version checks, the script will time out within 5 seconds if the F<arix.com> server is unavailable (when working offline or if the server is down).  Should the 5 seconds become annoying, users may pass this option to skip the version check.

=item B<--debug[=n]>

This option produces debugging output.  An optional integer increases the level of verbosity for this output.  If no integer is given, 1 is assumed.

=item B<--help, -h>

Displays a terse syntax message.

=item B<-V>

This option displays the version number of cpan2rpm itself.

=item B<-D>

This option runs cpan2rpm in the Perl debugger.  Useful for anyone willing to dig on my behalf.

=back

=head1 REQUIREMENTS

This script requires that RPM be installed.  Both the B<rpm> and B<rpm-build>
packages must be installed on the local machine.  Please see the RPM documentation (man rpm) for further information.

Additionally, the B<Perl> package will be needed :) and the CPAN module
(which is bundled with the Perl distribution) will need to be configured.  To configure CPAN (CPAN.pm or CPAN/MyConfig.pm) use the following:

    perl -MCPAN -e shell

For further information please refer to the CPAN manpage.

=head1 SUPPORTED PLATFORMS

At present, B<cpan2rpm> has been tested and is known to work under the following environments:

=over

=item B<Operating Systems>

The script has been tested with Linux RedHat 6.1, 6.2, 7.0, 7.2, 7.3 and 8.0 and SuSE 8.1.  Rumour has it it's been tested on Solaris as well but I don't know for sure.  See README.redhat6 for 6.x issues to be aware of.

=item B<Perl>

The script is known to work with Perl versions 5.005_03, 5.6.0, 5.6.1 and 5.8.0.

=item B<ExtUtils::MakeMaker>

This module is used for making and installing the CPAN modules.  However many of MakeMaker's versions are broken and incompatible with other versions.  For that reason, B<cpan2rpm> works well with versions < 5.91 and > 6.05 but in between it requires an upgrade.

=item B<Redhat Package Manager>

The RPM system has undergone a lot of change.  At present, B<cpan2rpm> runs on version 4.0.4-7x but requires certain special attention (see README for more information).  Earlier versions of RPM are borked in various ways and are not currently supported, though on SuSE version 3.0.6 appears to work.

=back

If you are running on a platform not listed above, do drop us a note and let us know!

=head1 AUTHOR

Erick Calder <ecalder@cpan.org>

=head1 ACKNOWLEDGEMENTS

The script was inspired by B<cpanflute> which is distributed with the rpm-build package from RedHat.  Many thanks to Robert Brown <bbb@cpan.org> for all his cool tricks, advice and patient support.

=head1 SUPPORT/BUGS/TODO

For help and thank you notes, e-mail the author directly.  To review known issues, report a new bug, submit a patch, or add to our wishlist, please visit:

F<http://rt.cpan.org/NoAuth/Bugs.html?Dist=cpan2rpm>

=head1 AVAILABILITY

The latest version of the tarball, RPM and SRPM may always be found at:

F<http://perl.arix.com/>

=head1 LICENCE AND COPYRIGHT

This utility is free and distributed under GPL, the Gnu Public License.

$Id: cpan2rpm,v 2.187 2003/02/21 04:54:06 ekkis Exp $

=cut
