#!/usr/bin/perl
use strict;
use warnings;

use IO::Handle;                     # 5.004 or higher
use Data::Dumper;
use XMLRPC::Lite;
use File::Basename;

{
   my $blogid   = "2";
   my $username = "hoge";
   my $password = "fuga!";
   my $proxyurl = "http://hoop.euqset.org/blog/mt-xmlrpc.cgi";
   my $jpgfile  = "/tmp/shibata10-s.jpg";

   my $bits = read_bin_file ($jpgfile);

   #------------------
   # upload the picture
   #
   my $picresult = XMLRPC::Lite
      -> proxy($proxyurl)
      -> call('metaWeblog.newMediaObject', $blogid, $username, $password,
      {
        'bits' => XMLRPC::Data->type('base64', $bits),
        'type' => "image/jpeg",
        'name' => "archives/images/".basename($jpgfile)
      }
      )
      -> result;
   if (!defined ($picresult))
   {
      die "failed $!";
   }
   else
   {
      print "url = (", $picresult->{'url'}, ")\n";
      #---------------
      # post the message
      #
      my $msgresult = XMLRPC::Lite
         -> proxy($proxyurl)
         -> call('metaWeblog.newPost', $blogid, $username, $password,
            {
               'title'             => "this is a test post via XMLRPC::Lite.",
               'description'       => "and this is\n\n" .
                                      "the body and a link to the picture\n\n" .
                                      "<img src=\"" . $picresult->{'url'} . "\">\n\nthe end :-)\n",
               'mt_allow_comments' => 1,  # must be int, not string
               'mt_allow_pings'    => 1   # must be int, not string
#              'mt_convert_breaks' => "", # string, see mt.supportedTextFilters for a valid value
#              'mt_text_more'      => "this is an extended entry.", # the extended entry
#              'mt_excerpt'        => "",
#              'mt_keywords'       => "",
#              'mt_tb_ping_urls'   => ??, #array of strings, ping URLs
            },
            1 # 1 = publish
            )
         -> result;
      if (!defined ($msgresult))
      {
         die "failed $!";
      }
      else
      {
         print Dumper ($msgresult);
      }
   }
}

sub read_bin_file
{
   my ($filename) = @_;

   #--------------------
   # read in the picture
   my $fh = IO::Handle->new();
   open($fh, $filename) or die "$!";
   local($/) = undef;  # slurp
   binmode($fh);
   my $bits  = <$fh>;
   close($fh);

   return $bits;
}
