#!/usr/bin/perl

use strict;
use warnings;
use utf8;

use Text::Dokuwiki::Parser;
use Text::Dokuwiki::Render::Markdown;

our $NAME    = 'dw2md';
our $VERSION = '0.01';

unless (@ARGV and -f $ARGV[0]) {
  warn "Usage: $NAME <infile> [<outfile>]\n";
  exit 1;
}

my $parser = Text::Dokuwiki::Parser->new;
my $render = Text::Dokuwiki::Render::Markdown->new;

my $text = '';
{
  open my $FH, '<', $ARGV[0]
    or die("open infile: $!\n");
  local $/ = undef;
  $text = <$FH>;
  close $FH;
}
my $tree = $parser->parse($text);
my $out  = $render->treewalk($tree);

if (my $outfile = $ARGV[1]) {
  open my $FH, '>', $outfile
    or die("open outfile: $!\n");
  print $FH $out;
  close $FH;
} else {
  print $out;
}

exit 0;