#!/usr/bin/env perl

# nopaste.pl - nopaste files to rafb.net
# sysdef@debiancenter.org
#
# (c) by juergen heine
# published under bsd license
#
# 2006-11-13 version 0.1.0
#

# modules
use LWP::UserAgent;
use HTTP::Request::Common 'POST';

# system settings
use constant HOST  => 'http://rafb.net';
use constant PASTE => '/paste/paste.php';

# user settings

  # username who nopaste to site, let blank for automatic user
  $user = "";

  # alternative comment
  $alt = "file:";

  # cut path if description is given
  $cut_given = 1;

  # cut path if description is not given
  $cut_not_given = 0;

#-------------------------------------------------------------

# if no user is set in config
if (! $user) {
  $user = $ENV{'USER'};
}

# get the file
$file = shift;

# get description
foreach (@ARGV ) {
  $descr .= $_ . " ";
}

# build the description
$display_file = $file;

if ($descr) {

  # description is given
  # remove the first space
  $display_file =~ s/^\ //;

  # cut the path?
  if ($cut_given) {
    $display_file =~ s/\/.*\///;
  }

  # append filename
  $descr .= "[ $display_file ]";

}
else {

  # is description is not given
  # cut the path?
  if ($cut_not_given) {
    $display_file =~ s/\/.*\///;
  }

  $descr = "$alt $display_file";

}

# list of extensions
%ext = (
  'cpp|cc|hh'       => 'C++',
  'c|h|y|l'         => 'C',
  'java'            => 'Java',
  'py'              => 'Python',
  'php'             => 'PHP',
  'pl|pm'           => 'Perl',
  'rb'              => 'Ruby',
  'sql'             => 'SQL',
);

# STOP if no filename given
die "usage: nopaste.pl <filename>" unless $file;

# nopaste the file
# open $file as F for reading
open F, "<$file" or die "nopaste.pl: $file: $!\n";

# get the file extension as $1 and serach for the $lang
$file =~ /.*\.(.+)$/;
foreach (keys %ext) {
    $lang = $ext{$_} if $1 =~ /^($_)$/;
}

$lang = 'Plain Text' unless $lang;

$r = LWP::UserAgent->new->request(
  POST HOST . PASTE, [
    nick => $user,
    text => join('', <F>),
    desc => $descr,
    lang => $lang
  ]
);

close F;

# try to paste
$p = $r->headers->header('Location');

# STOP: service not available
die "error: service not available '302 Found'.\n" unless 302 == $r->code;

# we were too fast?
if ( $p =~ /toofast/ ) {
  # wait and retry to paste
  sleep 11;
  $p = $r->headers->header('Location');
  die "error: service not available '302 Found'.\n" unless 302 == $r->code;
}

# STOP: wrong location
die "error: can't paste to '$p'\n" unless $p =~ /\.html$/;

# print the URL to console
print "$descr $p\n";

#EOF
