#!/usr/bin/perl
# 
# cpan2tgz - create slackware packages from cpan distributions 
# 
# Jason Woodward
# woodwardj at jaos dot org
# http://software.jaos.org
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
use strict;
use warnings;
use Config;
use CPAN;
use Getopt::Long;
use File::Find ();
use Errno;

our $VERSION = '0.6.8';
our $HAS_YAML = 1;
eval "no warnings 'all'; use YAML;"; if ($@) { $HAS_YAML = 0 }

$ENV{PATH} = "/bin:/sbin:/usr/bin:/usr/sbin";
my (
    %PACKAGE_CACHE_LIST,        $no_recursive,
    $no_install_after_building, $ignore_installed_deps,
    $tmp_dir,                   $package_dir,
    $nobanner,                  $upgrade_all,
    $build_tag,                 $build_number,
    $pkgext,
);
$tmp_dir      = "/tmp/";
$package_dir  = "/usr/src/";
$build_number = 1;
$pkgext       = 'txz';

usage() unless
  GetOptions(
    "no-recursive"    => \$no_recursive,
    "ignoreinstalled" => \$ignore_installed_deps,
    "no-install"      => \$no_install_after_building,
    "pkgdir=s"        => \$package_dir,
    "nobanner"        => \$nobanner,
    "upgrade-all"     => \$upgrade_all,
    "build-tag=s"     => \$build_tag,
    "build-number=i"  => \$build_number,
    "package-ext=s"  => \$pkgext,
  );
$build_tag ||= q[];

usage() unless (scalar(@ARGV) > 0 || $upgrade_all);

# cache installed packages
if ( opendir(my $pkg_log_dir,"/var/log/packages") ) {

  my @pkgs =
    map   { s/^(perl-[\w\-]+)-(([\w\.]+)-(\w+)-(\w+))$/$1/; $_;}
    grep  { m/^perl/ }
    grep  { ! m/^\.+$/}
    readdir($pkg_log_dir);

  foreach my $pkg (@pkgs) {
    $PACKAGE_CACHE_LIST{$pkg} = 1;
  }

  closedir($pkg_log_dir);

}

my @modules = @ARGV ? @ARGV
            : $upgrade_all ? CPAN::Shell->r()
            : ();

# now operate on each passed in module unless present in cache
foreach my $mod ( @modules ) {

  if (! exists $PACKAGE_CACHE_LIST{ "perl-" . $mod} || $ignore_installed_deps) {
    do_package($mod);
  }

}

sub do_package
{
  my ($module_name) = @_;
  return unless $module_name;

  my $module =  CPAN::Shell->expand('Module',$module_name)
                || CPAN::Shell->expand('Bundle',$module_name)
                || CPAN::Shell->expand('Distribution',$module_name);
  unless($module) {
    print STDERR "\nFailed to find module: $module_name","\n";
    exit(1);
  }

  my $pack;
  if ($module->can('distribution')) {
    $pack = $module->distribution;
  } else {
    $pack = $CPAN::META->instance('CPAN::Distribution',$module->cpan_file());
  }
  die "Failed to initialize CPAN::Distribution object for $module_name: $!" unless $pack;
  $pack->get(); # go ahead and fetch so we can inspect the source dir for arch info

  # try to extract some info about the module
  my $pkg_name = "perl-" . lc((split('/',$module->cpan_file))[-1]);
  my $final_pkg_version = (split('-',$pkg_name))[-1];
  (my $final_pkg_name = $pkg_name) =~ s/\-$final_pkg_version//;
  $pkg_name =~ s/\.tar.*?$//;

  # figure out the arch of the package, default to noarch
  my @xs_files = ();
  File::Find::find( sub { /^.*\.(?:xs|c|h|so)\z/s && push @xs_files, $_; }, $pack->dir);
  if ( $module->xs_file() || @xs_files ) {
    $pkg_name .= "-" . [split('-',$Config{archname})]->[0];
  } else {
    $pkg_name .= "-noarch";
  }
  $pkg_name .= "-${build_number}${build_tag}.${pkgext}";

  my $dest_dir = $tmp_dir . '/' . $module->id();

  if ( exists $PACKAGE_CACHE_LIST{$module->id()} || exists $PACKAGE_CACHE_LIST{$final_pkg_name} ) {
    print STDERR "\n\n",$module->id(),"/",$final_pkg_name,
      " deferred, already in queue or installed\n\n";
    return;
  }

  # store this so we don't process the same module twice
  # CPAN.pm complains about the module already processed in it's session
  $PACKAGE_CACHE_LIST{$module->id()} = 1;
  # this is for those packages that have names like TimeDate that may provide
  # multiple packages or a single package that differs from module->id()
  $PACKAGE_CACHE_LIST{$final_pkg_name} = 1;

  print "\n\nProcessing $module_name...\n\n";

  if ( $pack->isa_perl() ) {
    print STDERR "\nWill not install ",$module->id(),
      " because it is contained within Perl proper.\n";
    return;
  }

  # do an initial make so that we can get the dep info
  eval { $pack->make() or die $!; };
  if ( $@ ) {
    # make does not return the same when YAML or YAML::Syck is in
    # use and $! is set to an internal non-fatal value from a YAML
    # check
    if (!($!{ENOTTY} && $HAS_YAML)) {
      print "make ERROR [$module_name]: $!\n";
      exit(1);
    }
  }

  my @deps;
  if ($ignore_installed_deps && $pack->prereq_pm()) {
    my $deps = $pack->prereq_pm();

    # only get the deps that are not installed
    @deps = grep { defined && m/\w+/; }
      grep { ! m/^perl$/ }
      map { defined $PACKAGE_CACHE_LIST{$_} ? undef : $_ }
      map { m/requires$/ ? keys %{$deps->{$_}} : $_ }
      keys %{$deps};

  } elsif (my $deps = $pack->prereq_pm()) {

    # get all dependencies
    @deps = grep { $_ && m/\w+/; }
      grep { ! m/^perl$/ }
      map { defined $PACKAGE_CACHE_LIST{$_} ? undef : $_ }
      map { eval "no warnings 'all'; use $_;"; if ($@) { $_ } }
      map { m/requires$/ ? keys %{$deps->{$_}} : $_ }
      keys %{$deps};

  }

  # look at module prerequisites
  my @dep_pkg_names;
  if ( @deps > 0 ) {

    if ( $no_recursive ) {
      print "\n\nStopping.\n[", $module->id(), "] requires ", join(", ",@deps),"\n";
      exit(1);
    }

    print "\n\nhandling " . scalar(@deps)
      . " dependencies for $module_name: ",join(", ",@deps),"\n\n";

    sleep(1); # blah

    foreach my $dep ( @deps ) {
      local $@;
      print "FIXME: I don't deal with xsloader b/c make ?n/a?\n",next if $dep =~ m/xsloader/i;

      eval "no warnings 'all';use $dep;";
      # continue if installed, unless $ignore_installed_deps is set
      unless( $@ ) {
        next unless $ignore_installed_deps;
      }

      my $dep_pkg_name = do_package($dep);
      push(@dep_pkg_names,$dep_pkg_name) if $dep_pkg_name;
    }

  }

  clear_build_dir($dest_dir);
  
  # here we do steps to cleanup source before we build (per LinuxPackages.net perfect packages instructions)
  # this isn't pretty but it gets the job done
  my $pack_dir = $pack->dir();

  system("cd $pack_dir && chown -R root.root .");
  system("cd $pack_dir && find . -perm 777 -exec chmod 755 {} \\;");
  system("cd $pack_dir && find . -perm 555 -exec chmod 755 {} \\;");
  system("cd $pack_dir && find . -perm 444 -exec chmod 644 {} \\;");
  system("cd $pack_dir && find . -perm 666 -exec chmod 644 {} \\;");
  system("cd $pack_dir && find . -perm 664 -exec chmod 644 {} \\;");

  # install to the package build dir
  if ( -f "$pack_dir/Build" ) {
    system("cd $pack_dir && ./Build install --destdir=$dest_dir");
  } else {
    system("cd $pack_dir && make install DESTDIR=$dest_dir");
  }
  die "Failed to install to $dest_dir: $!" unless (-d $dest_dir);

  # copy documentation to the package build dir
  system("cd $dest_dir && mkdir -p ./usr/doc/$final_pkg_name-" . $module->cpan_version);
  system("cd $pack_dir && find . -type f -iregex '.*readme.*' -o -iregex '.*change.*' -o -iregex '.*todo.*' -o -iregex '.*license.*' -o -iregex '.*copying.*' -o -iregex '.*install.*' -o -iregex '.*\.txt' -o -iregex '.*\.html' |xargs -r -iZ cp Z $dest_dir/usr/doc/$final_pkg_name-" . $module->cpan_version . "/");

  # build a shell script to fixup the package like Pat's Perl SlackBuild
  open(my $script_fh,">$dest_dir/build.sh") or die "Failed to open build.sh for writing: $!";
  print $script_fh "cd $dest_dir\n";
  print $script_fh "find . | xargs file | grep 'executable' | grep ELF | cut -f 1 -d : | xargs strip --strip-unneeded 2> /dev/null\n";
  print $script_fh "find . | xargs file | grep 'shared object' | grep ELF | cut -f 1 -d : | xargs strip --strip-unneeded 2> /dev/null\n";
  print $script_fh "find ./usr/share/man/ -name '*.3' -exec gzip -9 {} \\; 2> /dev/null\n";
  print $script_fh "find ./usr/share/man/ -name '*.1' -exec gzip -9 {} \\; 2> /dev/null\n";
  print $script_fh "mv ./usr/share/man ./usr/\n" if (-d "$dest_dir/usr/share/man");
  print $script_fh "chown -R `stat --format '%u:%g' /usr/bin` ./usr/bin\n" if (-d "$dest_dir/usr/bin");
  print $script_fh "chmod 755 ./usr/bin/*\n" if (-d "$dest_dir/usr/bin");
  print $script_fh "chmod 644 ./usr/man/man?/*\n" if (-d "$dest_dir/usr/man");
  print $script_fh "rmdir ./usr/share\n" if (-d "$dest_dir/usr/share");
  print $script_fh "mkdir ./install\n";

  # generate the doinst.sh to fix perllocal.pod
  print $script_fh <<SCRIPT
PERLLOCALPOD=\`find . -name perllocal.pod\`
if [ -n "\$PERLLOCALPOD" ]; then
  cat >./install/doinst.sh <<EOF
#!/bin/sh

cat >> \${PERLLOCALPOD/.\\//} <<PLP

EOF
  cat \$PERLLOCALPOD >>install/doinst.sh
  echo "PLP" >>install/doinst.sh
  rm \$PERLLOCALPOD
fi
SCRIPT
;

  close($script_fh);
  system("cd $dest_dir && sh build.sh");
  system("cd $dest_dir && rm build.sh");

  
  # generate the slack-required file
  open(my $required_fh,">$dest_dir/install/slack-required") or die "Failed to open slack-required for writing: $!";
  print $required_fh "perl\n";
  foreach my $dep (@dep_pkg_names) {
    print $required_fh $dep,"\n";
  }
  close($required_fh);

  # generate the slack-desc file
  open(my $desc_fh,">$dest_dir/install/slack-desc") or die "Failed to open slack-desc for writing: $!";
  print $desc_fh "\n";
  print $desc_fh "# HOW TO EDIT THIS FILE:\n";
  print $desc_fh "# The \"handy ruler\" below makes it easier to edit a package description.  Line\n";
  print $desc_fh "# up the first '|' above the ':' following the base package name, and the '|'\n";
  print $desc_fh "# on the right side marks the last column you can put a character in.  You must\n";
  print $desc_fh "# make exactly 11 lines for the formatting to be correct.  It's also\n";
  print $desc_fh "# customary to leave one space after the ':'.\n";
  print $desc_fh "\n";
  print $desc_fh "         |-----handy-ruler------------------------------------------------------|\n";
  print $desc_fh "$final_pkg_name: $final_pkg_name " . $module->cpan_version() . " (Perl module)\n";
  print $desc_fh "$final_pkg_name:  \n";
  print $desc_fh "$final_pkg_name:  \n";
  print $desc_fh "$final_pkg_name:  \n";
  print $desc_fh "$final_pkg_name:  \n";
  print $desc_fh "$final_pkg_name:  \n";
  print $desc_fh "$final_pkg_name:  \n";
  print $desc_fh "$final_pkg_name:  Packaged by cpan2tgz\n" unless $nobanner;
  print $desc_fh "$final_pkg_name:  cpan2tgz by Jason Woodward <woodwardj\@jaos.org>\n" unless $nobanner;
  print $desc_fh "$final_pkg_name:  http://software.jaos.org/\n" unless $nobanner;
  print $desc_fh "$final_pkg_name:  \n";
  close($desc_fh);

  # finally, build the package
  system("cd $dest_dir && makepkg -l y -c n $package_dir/$pkg_name");
  die "Failed to build package $pkg_name: $!" unless (-f "$package_dir/$pkg_name");

  # install the package
  unless ($no_install_after_building) {
    system("installpkg $package_dir/$pkg_name") && exit;
  }

  clear_build_dir($dest_dir);

  return $final_pkg_name;
}

sub usage
{
  print "Jason Woodward <woodwardj at jaos dot org>\n";
  print "Usage: $0 [option(s)] [modules(s)]\n";
  print "  --no-recursive     do NOT build required modules","\n";
  print "  --ignoreinstalled  rebuild required modules that are already installed\n";
  print "  --no-install       do NOT install the generated package(s)\n";
  print "  --pkgdir           location to place the generated package(s)\n";
  print "  --nobanner         Leave out the cpan2tgz banner in the description\n";
  print "  --upgrade-all      Create packages (and install) for all outdated modules\n";
  print "  --build-tag        Specifies the package build tag\n";
  print "  --build-number     Specifies the package build number\n";
  print "  --package-ext      Specifies the package extension (default: txz)\n";

  exit(1);
}

sub clear_build_dir
{
  my ($dest_dir) = @_;
  return unless $dest_dir;
  system("rm -r $dest_dir/*") if (-d $dest_dir);
  system("rmdir $dest_dir") if (-d $dest_dir);
}

1;

__END__

=head1 NAME

cpan2tgz - create Slackware GNU/Linux packages from CPAN Perl module distributions

=head1 SYNOPSIS

cpan2tgz [option(s)] [module(s)]

options: [--no-recursive] [--ignoreinstalled] [--no-install] [--pkgdir] [--build-tag] [--build-number] [--package-ext]

cpan2tgz --upgrade-all

=head1 DESCRIPTION

cpan2tgz is a tool to create Slackware GNU/Linux packages from CPAN Perl module distributions.  cpan2tgz was inspired by cpan2rpm.

=head1 OPTIONS

=over

=item B<--no-recursive>

This will NOT build required module(s).  Otherwise dependencies are built and installed as cpan2tgz traverses the dependency tree of the specified Perl module(s).  This can be dangerous.  It might be best to install one at a time.

=item B<--ignoreinstalled>

This option specifies to build packages for required modules even if the module is found to be present and installed on the system.

=item B<--no-install>

Do NOT install the generated package(s).

=item B<--pkgdir>

This option specifies the final location to place the generated package(s).  Defaults to /usr/src.

=item B<module(s)>

A series of Perl modules to install, ie Data::Dumper

=item B<--upgrade-all>

Create packages and install for all outdated modules on the system.  Do not pass in module names on the command line.

=item B<--build-tag>

Set the package's build tag, foo-0.1-arch-1buildtag.tgz.

=item B<--build-number>

Set the package's build number, foo-0.1-arch-build_number.tgz.

=head1 NOTES

cpan2tgz uses the CPAN Perl module.  A working CPAN/Config.pm is assumed.  If CPAN has not been initialized prior to running cpan2tgz, it will be initialized on the first run.

=head1 AUTHOR

Jason Woodward <woodwardj@jaos.org>

http://software.jaos.org/

=head1 SEE ALSO

installpkg(8), makepkg(8), removepkg(8), pkgtool(8), upgradepkg(8),

=pod OSNAMES

any

=pod SCRIPT CATEGORIES

Unix/System_administration

=cut
