#!/usr/bin/env perl

# Perl LPix uploader client
# Requires that the perl LWP module be installed.

use strict;
use warnings;

# *** Change these!
my $user = "Polsy";
my $pass = "myPassword";
my $gallery = "Default";

use LWP;
use HTTP::Request::Common;

my %errors = ('err2' => 'Invalid username/password', 'err3' => 'Not an image', 'err4' => 'File too large' );
my $ua = LWP::UserAgent->new;

for my $image (@ARGV) {
  my $sz = (-s $image);
  if($sz > 2048*1024) {
    print "$image\n";
    print "  Images have a maximum allowable size of 2048KB, skipping\n\n";
    next;
  }

  # Check file can be opened ok
  -r $image || die "Couldn't open $image: $!";

  # Create HTTP request for file
  my $req = POST("https://lpix.org/api",
          "Content-Type" => "form-data",
          "Content"      => [ "username" => $user,
                              "password" => $pass,
                              "gallery" => $gallery,
                              "output" => "xml",
                              "file" => [$image],
                            ]);
  # Make request
  my $resp = $ua->request($req);

  print "$image\n";

  # Failed?
  if(! $resp->is_success) {
    warn "Upload failed, error: ", $resp->status_line, "\n";
    next;
  }

  # Blank these out in case they're not returned for some reason
  my($imageURL, $thumbURL) = ("", "");

  # Pick the interesting bits out of the XML
  for (split /\n/, $resp->content) {
    if (m#<err type="([^"]+)"\s*/>#) {
      my $errTxt = $errors{$1} || "(unknown error)";
      warn "  Uploading error $1 : $errTxt\n";
    }

    if (m#<imageurl>([^<]+)</imageurl>#) {
      $imageURL = $1;
    }
    if (m#<thumburl>([^<]+)</thumburl>#) {
      $thumbURL = $1;
    }
  }

  if($imageURL) { print "[img]", $imageURL, "[/img]\n"; }
  if($thumbURL) { print "[timg]", $thumbURL, "[/timg]\n"; }

  print "\n";
}
