#!/usr/bin/perl

# Usage:
#  ./me.pl MT_EXPORT_FILE static_html_files... > RESULT_MT_EXPORT_FILE

use strict;

use Jcode;
use FileHandle;
use Data::Dumper;

my $mtExportFile = shift @ARGV;
if ( !-r $mtExportFile ) {
	die "Please specify valid MT export file";
}

my @files;
# Extract Windows' wild cards
while ( my $i = shift @ARGV ) {
	push( @files, glob( $i ) );
}

sub EucSlurp {
	my $fn = shift @_;
	return do {
		local $/;
		my $fh = FileHandle->new( $fn, 'r' )
			or return; # エラー
		local $_ = <$fh>;
		s/\x0D\x0A|\x0D|\x0A/\n/g;
		jcode( $_ )->euc;
	};
}

select STDERR;
$| = 1;

print "Reading static files:";
my %entries;
foreach my $file ( @files ) {
	my $cnt = EucSlurp( $file )
		or do {
			warn "No such file: $file";
			next;
		};
	my $this;

	$this->{filename} = $file;

	sub RmWS {
		my $s = shift @_;
		$s =~ s/^\s+//s;
		$s =~ s/\s+$//s;
		$s =~ s/\n+/ /s;
		return $s;
	}

	$this->{title} = RmWS( ( $cnt =~ m|<title[^>]*>(.*?)</title>|si )[0] );
	my $rdf = ( $cnt =~ m|<rdf:RDF[^>]*>(.*?)</rdf:RDF|s )[0];
	$rdf =~ s|<![CDATA[.*?]]>||s;
	$this->{dcTitle} = RmWS( ( $rdf =~ m|dc:title="(.*?)"\n|s )[0] );
	$this->{dcDate} = RmWS( ( $rdf =~ m|dc:date="(.*?)"\n|s )[0] );
	# Seesaaには "" の中の " をエスケープしないバグがあるので、
	# "\n をターミネータと見なして対処
=rem
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
         xmlns:Trackback="http://madskills.com/public/xml/rss/module/Trackback/"
         xmlns:dc="http://purl.org/dc/elements/1.1/">
<rdf:Description
    rdf:about="http://..........."
    trackback:ping="http://........."
    dc:title="..........."
    dc:identifier="http://.........."
    dc:description="..............."
    dc:creator="........."
    dc:subject="......"
    dc:date="2006-10-29T03:28:55+09:00"
/>
</rdf:RDF>
=cut
#DATE: 10/29/2006 03:28:55
	$this->{mtDate} =
		sprintf(
			"%02d/%02d/%04d %02d:%02d:%02d",
			( split( /[^0-9]/, $this->{dcDate} ) )[ 1, 2, 0, 3, 4, 5 ]
		);

	if (
		!$this->{dcTitle}
		|| !$this->{dcDate}
	) {
		warn "Cannot properly process $file";
		warn jcode( Dumper( $this ) )->sjis;
		my $key = <>;
	} else {
		print "."
	}

	#$entries{ $this->{mtDate}."\t".$this->{dcTitle} } = $this;
	$entries{ $this->{mtDate} } = $this;
}
print "\n";

open( R, "<$mtExportFile" );
print "Processing MT export file $mtExportFile:";

my $entrySeparator = '--------';
my $dataSeparator = '-----';

binmode STDOUT;

my $anEntry;
while ( my $line = <R> ) {
	$line =~ tr/\r\n//d;
	if ( $line eq $entrySeparator ) {
		$anEntry = jcode( $anEntry )->euc;

		my $propBlock = ( split( /$dataSeparator\n/, $anEntry ) )[0];
		my $rest = substr( $anEntry, length( "$propBlock$dataSeparator\n" ) );

		my %props;
		foreach my $prop ( split( /\n/, $propBlock ) ) {
			my $key = ( split( /:/, $prop ) )[0];
			my $val = substr( $prop, length( "$key:" ) );
			$val =~ s/^\s*//;
			$props{ $key } = $val;
		}
		my $bogoUniq = $props{ 'DATE' }; #."\t".$props{ 'TITLE' };

		if ( exists $entries{ $bogoUniq } ) {
			my $mark =
				'XORIGINALFILENAME: '
				. $entries{ $bogoUniq }->{filename}
				;
			print STDOUT "$mark\n";
			print STDOUT $propBlock;
			print STDOUT "$dataSeparator\n";
			unless ( $rest =~ s/^BODY:\n/BODY:\n<!-- $mark -->/s ) {
				die "Hmmm... Where goes the body part for "
					. jcode( $bogoUniq )->sjis
					. '?'
					;
			}
			print STDOUT $rest;
			print STDOUT "$entrySeparator\n";
			print ".";
		} else {
			die "Cannot find static file for " . jcode( $bogoUniq )->sjis;
		}
		$anEntry = '';
		next;
	}
	$anEntry .= "$line\n";
}
close( R );
