#!/usr/bin/perl

use warnings;
use strict;

use Data::Dump qw/dump/;
use File::Slurp;

my $debug = 0;

my $post;

my ($n,$v);

while(<>) {
	chomp;

	if ( $n ) {
		if ( /^-----/ ) {
			$post->{$n} .= " $v";
			undef $n;
		} else {
			$v .= "$_\n";
			next;
		}
	} elsif ( /([^:]+):(.*)/ ) {
		($n,$v) = ($1,$2);
		if ( length($v) > 0 ) {
			$v =~ s{^\s+}{};
			$post->{$n} = $v;
			undef $n;
		}
	} elsif ( /^$/ ) {
		next;
	} elsif ( /^--------$/ ) {

		warn "# post = ", dump($post) if $debug;

		my $path = "posts/$post->{BASENAME}.html";


		my $tags = join(' ', map { "categories/$_" } split( m/ /, $post->{CATEGORY} ) );
		$tags   .=      ' ' if $tags;
		$tags   .= join(' ', map { "tags/$_" }       split( m/,/, $post->{TAGS} ) );

		my ( $dd, $mm, $yyyy, $h, $m, $s, $ampm ) = split(m{[/ :]}, $post->{DATE});
		$h += 12 if $ampm eq 'PM';
		my $t = sprintf('%04d-%02d-%02dT%02d:%02d:%02d', $yyyy, $mm, $dd, $h, $m, $s);

		write_file $path,
		qq|
[[!meta title="$post->{TITLE}" ]]
[[!meta date="$t" ]]
[[!meta updated="$t" ]]
[[!tag $tags ]]
		|
		. "\n"
		. $post->{BODY}
		;

		my $cmd = qq|svn add $path && svn commit -m "$post->{TITLE}" && svn propset -rHEAD --revprop svn:date $t.000000Z|;
		warn "## $cmd\n";
		system($cmd);
		warn "# $path $t ", -s $path, $/;

		$post = {};
	}

}
