#!/usr/bin/env perl

use strict;
use warnings;

use Pinto;
use Try::Tiny;
use Path::Class;
use File::Find::Rule;

#------------------------------------------------------------------------------

@ARGV >= 2 or die "Must specify CPAN_DIR and PINTO_DIR";

my $cpan_dir = shift;
-d $cpan_dir or die "$cpan_dir does not exit";

my $pinto_dir = shift;
-d $pinto_dir or die "$pinto_dir does not exist";

my $limit = shift;

#------------------------------------------------------------------------------

open my $log_fh, '>', 'logfile.log' or die $_;

#------------------------------------------------------------------------------

my $counter = 1;
my $pinto   = Pinto->new(root => $pinto_dir);
my $rule    = File::Find::Rule->file->name('*.tar.gz')->start("$cpan_dir/authors/id");

while (my $archive = $rule->match) {

    last if defined($limit) and $counter > $limit;

    my $dist_path = file($archive)->relative($cpan_dir)->cleanup;
    my $author    = (split '/', $dist_path)[4];

    next if $dist_path->basename =~ /^Acme-BadExample/;          # Hangs
    next if $dist_path->basename =~ /^(syb|ora)?perl-?[\d\.]+/i; # Don't want

    my $now = localtime;
    my $msg = "Importing $dist_path from CPAN";
    print "$counter: $now: $msg\n";

    my %args = ( archives   => [$archive],
                 author     => $author,
                 message    => $msg,
                 no_recurse => 1 );

    try   { $pinto->run(Add => %args) }
    catch { s/(\n.*)//msg; print {$log_fh} "$archive: $_\n" };

   $counter++;
}
