#!/usr/bin/perl -w
use strict;
use warnings;
use Fatal qw(open close);
use Getopt::Long;
use Pod::Usage;
use File::Spec;
use feature qw(switch);

=head1 NAME

vimblog-convert -- Convert vimblog to ikiwiki

=head1 SYNOPSIS

vimblog-convert --srcdir ~/.blog/entries --dstdir ~/ikiblog

=cut

my $srcdir;
my $dstdir;

GetOptions(
	'srcdir=s' => \$srcdir,
	'dstdir=s' => \$dstdir,
) or pod2usage();

unless($srcdir && $dstdir && -d $srcdir && -d $dstdir) {
	pod2usage('must specify --srcdir and --dstdir');
}

makeblog( $dstdir );
maketoptag( $dstdir );

my $postdir = File::Spec->catdir( $dstdir, 'blog');
unless( -d $postdir ) {
	mkdir $postdir;
}

my $tagdir = File::Spec->catdir( $dstdir, 'tag');
unless( -d $tagdir ) {
	mkdir $tagdir;
}

while(my $path = <$srcdir/*>) {
	my ($crap, $dirs, $file) = File::Spec->splitpath( $path );

	my $touchstamp = $file;
	$touchstamp =~ s/(\d\d)$/\.$1/;

	open(my $infh, '<', $path);
	my $postbuf = '';
	my $more_flag = 0;
	while(my $line = <$infh>) {
		given( $line ) {
	
			when (/^Subject:\s+(.*)/i) {
				$postbuf .= qq{[[!meta title="$1"]]\n};
				next;
			}
			when (/^Content-Type:/i) {
				# Ignore
				next;
			}
			when (/^Alias:\s+(.*)/i) {
				$file = $1 if $1;
				next;
			}
			when (/^Tags:\s+(.*)/i) {
				my @tags = map { 
					s/\s+//;
					$_;
				} split(/\s*,\s*/, $1);
				
				$postbuf .= q{[[!tag } . join(' ',@tags) . qq{]]\n};
				foreach my $t (@tags) {
					maketag( $tagdir, $t);
				}
				next;
			}
			when (/<read-more>/) {
				$postbuf .= qq{[[!more text="""};
				$more_flag = 1;
				next;
			}
		
			default  { $postbuf .= $_; }
		}
	}
	if($more_flag) {
		$postbuf .= qq{"""]]};
	}

	my $outfile =  File::Spec->catfile( $postdir, $file . '.mdwn' );
	open(my $outfh, '>', $outfile);
	print $outfh $postbuf;
	close $outfh;

	system("touch -t $touchstamp $outfile");
}

sub makeblog
{
	my($tgtdir) = @_;

	my $blogfile = File::Spec->catfile( $tgtdir, 'blog.mdwn');
	if( -r $blogfile ) {
		return;
	}

	open(my $outfh, '>', $blogfile);
	print $outfh <<"END";
[[!pagestats pages="tag/*"]]

[[!inline pages="blog/* and !*/Discussion" actions=yes rootpage="./blog"]]
END
	close $outfh;
}

sub maketoptag
{
	my($tgtdir) = @_;

	my $tagfile = File::Spec->catfile( $tgtdir, 'tag.mdwn');
	if( -r $tagfile ) {
		return;
	}

	open(my $outfh, '>', $tagfile);
	print $outfh <<"END";
[[!pagestats style="table" pages="tag/*"]]
END
	close $outfh;
}

sub maketag
{
	my($tgtdir, $tagname) = @_;

	my $tagfile = File::Spec->catfile( $tgtdir, $tagname . '.mdwn');
	if( -r $tagfile ) {
		return;
	}
	open(my $outfh, '>', $tagfile);
	print $outfh <<"END";
[[!inline pages="link(tag/$tagname)" actions=yes]]
END
	close $outfh;
}
