#!/usr/bin/perl
# Name: mail2mt-newpost.pl
# Version: 01-00
# Copyright: 2006.01.07 shibata@luky.org
# Usage: perl mail2mt-newpost < entire-mail.file

use strict;
use warnings;

use MIME::Parser;
use HTTP::Date;
use Jcode;
use Data::Dumper;
use XMLRPC::Lite;

#-------------------------------------Blog configs
my $blogid   = "2";
my $username = "hoge";
my $password = "fuga";
my $proxyurl = "http://blog.uriuri.com/mt/mt-xmlrpc.cgi";

#-------------------------------------Mailing list configs
my $MLID     = "x-ml-name";
my $MLCOUNT  = "x-mail-count";

#main
#-------------------------------------Parsing Mail Header and Body
my $parser = new MIME::Parser;
my $entity = $parser->parse(\*STDIN);

my $subject = $entity->head->get('subject',0);
my $date = $entity->head->get('date',0);
chomp (my $mlname = $entity->head->get($MLID,0));
chomp (my $mlcount = $entity->head->get($MLCOUNT,0));
my $body =  $entity->bodyhandle;
my $mailbody =  $body->as_string;

#$head->unfold;
#$head->decode;

$subject = Jcode->new($subject)->mime_decode->utf8;
$mailbody = Jcode->new($mailbody)->utf8;

my $time = HTTP::Date::time2iso(str2time($date));

#print "Title: ",$subject;
#print "Category: ",$mlname;
#print "Date: ",$time,"\n";
#print "\n";
#print $mailbody;

#-------------------------------------post new Blog from ML 
print "[".$mlname."-".$mlcount."] ";
my $postid = XMLRPC::Lite
	-> proxy($proxyurl)
	-> call('metaWeblog.newPost', $blogid, $username, $password,
		{
		'title'             => $subject,
		'description'       => $mailbody,
		'dateCreated'       => $time,
		'mt_allow_comments' => 1,
		'mt_allow_pings'    => 1,
#		'mt_convert_breaks' => "",
#		'mt_text_more'      => "this is an extended entry.",
		'mt_excerpt'        => "",
		'mt_keywords'       => $mlcount,
#		'mt_tb_ping_urls'   => "", #array of strings, ping URLs
		},
		0 # 1 = publish
	)
	-> result;

#-------------------------------------get Category list to prepare category ID
if (defined ($postid) && $mlname)
{
	my $categories = XMLRPC::Lite
		-> proxy($proxyurl)
		-> call('mt.getCategoryList',
			$blogid,
			$username,
			$password
		)
		-> result;
       	my $i = 0;
       	my $catId = 0;
	do {
        	if( $mlname =~ /$categories->[$i]->{'categoryName'}/) {
#			print $categories->[$i]->{'categoryId'}." = ";
#			print $categories->[$i]->{'categoryName'}."\n";
			$catId = $categories->[$i]->{'categoryId'};
		}
	$i++;
	}
	until(!$categories->[$i]->{'categoryName'});

#-------------------------------------set Category of just posted Id
	my $res = XMLRPC::Lite
		-> proxy($proxyurl)
		-> call('mt.setPostCategories',
			$postid,
			$username,
			$password,
			[
				{
				'categoryId'   => $catId,
				'isPrimary'    => 1
				}
			]
		)
		-> result;
	print "set category $! ";
}
else
{
	die "failed $!";
}
#-------------------------------------publish post
my $res = XMLRPC::Lite
	-> proxy($proxyurl)
	-> call('mt.publishPost',
		$postid,
		$username,
		$password,
	)
	-> result;
print "publish post $!\n";
