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

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;
}

# 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);

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