#!/usr/bin/perl 

use 5.10.0;

use strict;
use warnings;

use Dist::Release;
use Getopt::Long;
use Module::Locate 'locate';
use Pod::Usage;

use Module::Pluggable search_path => 'Dist::Release::Action', sub_name => 'actions';
use Module::Pluggable search_path => 'Dist::Release::Check',  sub_name => 'checks';


my %options;
GetOptions( \%options, 
    'list!',
    'action=s@',
    'check=s@',
    'checks!',
    'doit!',
    'available!',
);

if ( $options{available} ) {
    say '--- checks';
    for( sort { $a cmp $b } checks() ) {
        say step_oneliner( $_ );
    }
    say '--- actions';
    say for sort { $a cmp $b } actions();
    exit;
}

sub step_oneliner {

    no warnings qw/ uninitialized /;
    my $pod_output;
    local *STDOUT;
    open my $fh, '>', \$pod_output; 

    pod2usage(  
        -input => locate($_[0]), 
        -output => $fh , 
        -exitval => 'NOEXIT',
        -verbose => 99,
        -sections => 'NAME' );

    $pod_output =~ s/^(Name:)?\s*//mg;
    $pod_output ||= $_[0];
    $pod_output =~ s/\n/ /g;

    $pod_output =~ s/Dist::Release::(Action|Check):://;

    return $pod_output;
}

my %args;
if ( $options{action} and @{$options{action}} ) {
    $args{actions} = $options{action};
    $args{checks} ||= [];
}
if ( $options{check} and @{$options{check}} ) {
    $args{checks} = $options{check};
    $args{actions} ||= [];
}

$args{check_only}=1 if  $options{checks};
$args{pretend}= !$options{doit};

my $rel = Dist::Release->new( %args );

if ( $options{list} ) {
    $rel->print_steps;
    exit;
}


$rel->run;

__END__

=head1 NAME

distrelease - releases a distribution to CPAN

=head1 SYNOPSIS

B<distrelease>  [ -doit ]

=head1 DESCRIPTION

This is the command-line interface to the Dist::Release
process.

=head1 OPTIONS

=over

=item --available

Prints out all the available checks and actions.

=item --list

Prints out all the checks are actions that would be performed and exits.

=item --check I<checks>

If B<--check> is provided, the given checks will be used 
instead of the ones provided in the configuration file.

Example:

    distrelease --check Manifest UpdatedVersion

=item --action I<actions> 

If B<--action> is provided, the given actions will be used
instead of the ones provided in the configuration file.

Example:

    distrelease --action Github CPANUpload


=back

=head1 version

This documentation refers to Dist::Release version 0.0_1.

=head1 AUTHOR 

Yanick Champoux, <yanick@cpan.org>.

=head1 LICENSE AND COPYRIGHT

Copyright (c) 2008 Yanick Champoux (<yanick@cpan.org>). All rights reserved.

This module is free software; you can redistribute it and/or
modify it under the same terms as Perl itself. See L<perlartistic>.