#!/usr/bin/perl -w

# brayar2mt.pl
#
# 08/27/2006 04:25:34 PM CEST Dobrica Pavlinusic <dpavlin@rot13.org>

use strict;
use File::Find;
use File::Slurp;
use POSIX qw/strftime/;
use Encode qw/from_to/;

my $blog;

sub time2date {
	my $t = shift || die "no time?";
	return strftime('%m/%d/%Y %r', localtime($t));
}

find({ wanted => sub {
	my $p = $_;

	$p =~ s!^\./!!;

	return unless ($p =~ m!^(\w+/)?(\d+)\.(txt|comments)$!);
	return unless (-s $p);

	my ($category,$nr,$type) = ($1,$2, $3);

warn "## $p\n";

	my $body = read_file($p) || die "can't read $p: $!";

	my $title = $1 if ($body =~ s/^(.+?)[\n\r]+//s || die "can't find title in $body");

	my $date = time2date( (stat($p))[9] );		# mtime

	$category ||= '';
	$category =~ s!/!!g;

	warn "$category | $nr | $type | $date | $title\n";

	if ($type eq 'txt') {

		my $post = qq{--------
AUTHOR: dpavlin
TITLE: $title
STATUS: Publish
ALLOW COMMENTS: 1
CONVERT BREAKS: __default__
ALLOW PINGS: 1
} . ( $category ? "CATEGORY: $category\n" : '' ) . qq{
DATE: $date
-----
BODY:
$body
-----
};

		$blog->{$nr}->{post} = $post;
	} elsif ($type eq 'comments') {

		foreach my $c (split(/\n-----\n/, $body)) {
			my $comment;
			foreach my $l (split(/\n/, $c)) {
				my ($k,$v) = split(/:\s+/, $l);
				$comment->{$k} = $v;
			}

			$date = time2date( $comment->{epoch} ) if ($comment->{epoch});

			$blog->{$nr}->{post} .= qq{COMMENT:
AUTHOR: $comment->{author}
URL: $comment->{url}
DATE: $date
$comment->{content}
-----
};
		}

	} else {
		die "unknown type $type\n";
	}

}, follow => 1, no_chdir => 1}, '.');

foreach my $nr (sort { $a <=> $b } keys %$blog) {
	my $post = $blog->{$nr}->{post};
	from_to($post, 'iso-8859-2', 'utf-8');
	print "$post\n";
}
print "--------\n";


