#!perl
use strict;
use warnings;
use Carp;
use CPAN::Uploader;
use File::Spec;

=head1 NAME

cpan-upload - upload a distribution to the CPAN

=head1 USAGE

  usage: cpan-upload [options] file-to-upload
    -v --verbose       enable verbose logging
    -h --help          display this help message
    --dry-run          do not actually upload anything
                     
    -u --user          your PAUSE username
    -p --password      the password to your PAUSE account
    -d --directory     a dir in your CPAN space in which to put the file
    --http-proxy       URL of the http proxy to use in uploading

=head1 CONFIGURATION

If you have a C<.pause> file in your home directory, it will be checked for a
username and password.  It should look like this:

  user EXAMPLE
  password your-secret-password

=head1 SEE ALSO

L<CPAN::Uploader>

=cut

use Getopt::Long::Descriptive;
$Getopt::Long::Descriptive::MungeOptions = 1;

my %arg;

my $home = $ENV{HOME} || '.';
my $rc   = File::Spec->catfile($home, '.pause');

# Process .pause
open my $pauserc, '<', $rc or die "can't open $rc for reading: $!";

while (<$pauserc>) {
  chomp;
  next unless $_ and $_ !~ /^\s*#/;

  my ($k, $v) = /^\s*(\w+)\s+(.+)$/;
  croak "multiple enties for $k" if $arg{$k};
  $arg{$k} = $v;
}

# This nonsensical hack is to cope with Module::Install wanting to call
# cpan-upload -verbose; it should be made to use CPAN::Uploader instead.
$ARGV[0] = '--verbose' if @ARGV == 2 and $ARGV[0] eq '-verbose';

# Process arguments
my ($opts, $usage) = describe_options(
	"usage: %c [options] file-to-upload",

  [ "verbose|v" => "enable verbose logging" ],
  [ "help|h"    => "display this help message" ],
  [ "dry-run"   => "do not actually upload anything" ], 
  [],
  [ "user|u=s"      => "your PAUSE username" ],
  [ "password|p=s"  => "the password to your PAUSE account" ],
  [ "directory|d=s" => "a dir in your CPAN space in which to put the file" ],
  [ "http-proxy=s"  => "URL of the http proxy to use in uploading" ],
);

if ($opts->{help}) {
  print $usage->text;
  exit;
}

die "Please provide a file name.\n".$usage unless my $file = $ARGV[0];

$arg{debug}  = 1 if $opts->{verbose};
$arg{subdir} = $opts->{directory} if defined $opts->{directory};

$arg{ $_ } = $opts->{ $_ }
  for grep { defined $opts->{ $_ } } qw(dry_run user password http-proxy);

if (!$arg{password}) {
  require Term::ReadKey;
  local $| = 1;
  print "PAUSE Password: ";
  Term::ReadKey::ReadMode('noecho');
  chop($arg{password} = <STDIN>);
  Term::ReadKey::ReadMode('restore');
  print "\n";
}

CPAN::Uploader->upload_file(
  $file,
  \%arg,
);
