#!/usr/bin/perl
use LWP::UserAgent;
use Getopt::Long;
use Sys::Hostname;
#use Data::Dumper;

sub usage() {
    print "Options:\n";
    print "    -h This message \n";
    print "    -l Use long hostname (i.e. user\@host)\n";
    print "    -n Nick to use for post\n";
    print "    -r Length of time to keep the post d, m, or f \n\tfor day, month, or forever respectively\n";
    exit;
}

my $ua = new LWP::UserAgent;
$ua->env_proxy(); 
my $url = 'http://pastebin.freeswitch.org/';
my $line;
my $text;
my $login = getlogin() || getpwuid($<) || "Anonymous";
my $host = hostname();
my @getopt_args = (
    'n=s', #nick to use for paste
    'H=s', #highlighting to use 
    'r=s', #how long to keep the paste [dmf]
    'l', #use long name user@host
    'h', # help, shows usage()
    'd' #debug
);

# Options Stuff
Getopt::Long::config("noignorecase", "bundling");
GetOptions(\%options, @getopt_args);
usage() if $options{h};
$debug = 1 if $options{d};
my $nick = length($options{n}) > 0 ? $options{n} : $login;
$nick = $options{l} ? $nick . "_AT_" . $host : $nick;
my $highlighting = length($options{H}) > 0 ? $options{H} : 'text';
my $keep = length($options{r}) > 0 ? $options{r} : 'd';
if($debug) {
    print "Nick is $nick\nhighlighting is $highlighting\nKeep for $keep\n"; 
}
#exit;


while($line = <STDIN>) {
    $text .= $line;
}
push @{ $ua->requests_redirectable }, 'POST';
# this should be smart enough to get the realm on its own.... 
# maybe in a future version, i'll add that
$ua ->credentials(
    'pastebin.freeswitch.org:80', 
    'the login and password is pastebin/freeswitch',
    'pastebin' => 'freeswitch'
    );
my $response = $ua -> post($url, 
    {
	paste => 'Send',
	remember => "0",
        poster => "$nick", 
	format => "$highlighting",
	code2 => "$text",
	expiry => "$keep"
    }
);

if($debug) {
    print $response -> content;
    print "---- Dumper Start ----\n";
    print Dumper $response;
    print "---- Dumper Stop ----\n";
}
print "Your Post can be seen at: " 
.  $response->{_previous}->{_headers}->{location} . "\n";
