#!/usr/bin/perl
#
# This file is part of Task-Dist-Zilla
#
# This software is copyright (c) 2010 by Jerome Quelin.
#
# This is free software; you can redistribute it and/or modify it under
# the same terms as the Perl 5 programming language system itself.
#

use strict;
use warnings;

use DB_File;
use List::MoreUtils qw{ firstidx };
use Regexp::Assemble;

# ignore dzil v1 plugins
my @dzilv1 = qw{ AllFiles InstallDirs PodTests };
my $remove = Regexp::Assemble->new;
$remove->add("$_\$") for @dzilv1;

# ignore list
$remove->add("$_\$") for (
    'SanityTests', # deprecated
);

# fetch available plugins/bundles
my $modlist = '/home/cpan/modules/02packages.details.txt.gz';

# update the module
my $task = 'lib/Task/Dist/Zilla.pm';
my @lines;
tie @lines, 'DB_File', $task, O_RDWR|O_CREAT, 0666, $DB_RECNO
    or die "can't open $task: $!";

# update plugins
my @plugins =
    map  { "=pkg $_\n" }
    grep { ! /$remove/ }
    map  { (split /\s+/, $_)[0] }
    grep { ! m!\s\S+/Dist-Zilla-\d\.\d{6}.tar.gz$! }
    qx{ zgrep Dist::Zilla::Plugin:: $modlist };
my $p1 = firstidx { /^=pkgroup Plugins$/ } @lines;
my $p2 = firstidx { /^=pkgroup Plugin bundles$/ } @lines;
splice @lines, $p1+2, $p2-$p1-2, @plugins;

# update bundles
my @bundles =
    map { "=pkg $_\n" }
    map { (split /\s+/, $_)[0] }
    grep { ! m!\s\S+/Dist-Zilla-\d\.\d{6}.tar.gz$! }
    qx{ zgrep Dist::Zilla::PluginBundle:: $modlist };
my $b1 = firstidx { /^=pkgroup Plugin bundles$/ } @lines;
my $b2 = firstidx { /^=head1 SEE ALSO$/ } @lines;
splice @lines, $b1+2, $b2-$b1-2, @bundles;


untie @lines;
