#!/usr/bin/env perl
use strict;

my $str = "";
my $curls = 0;

sub flush_nostr {
  if ($curls) {
    $str .= " }}}\n\n";
    $curls = 0;
  }
}

sub flush {
  if ($str ne "") {
    $str =~ s/(\[.*\])/{{{$1}}}/g;
    $str =~ s,http://wiki.dovecot.org/(\w+),[wiki:$1 $1],g;
    $str =~ s/\n$//g;
    print "$str\n\n";
    $str = "";
  }
  flush_nostr();
}

print "#acl All:read\n";
my $first = 1;
while (<>) {
  next if (/^ *##$/);

  if (/^ *## (.*)$/) {
    flush();
    if ($first) {
      print "= $1 =\n[[TableOfContents]]\n";
      $first = 0;
    } else {
      print "== $1 ==\n";
    }
    next;
  }
  if (/^ *$/) {
    # new paragraph
    flush();
    next;
  }
  if (/^ *# *$/) {
    # new commented paragraph
    flush_nostr();
    $str .= "\n\n" if ($str ne "");
    next;
  }
  if (/^ *# ([^ ].*)$/) {
    # comment about the following setting
    my $val = $1;
    flush_nostr();
    $str .= " " if ($str ne "" && $str =~ /[^\n]$/);
    $str .= $val;
    next;
  }
  if (/^ *# ( *.*)$/) {
    # some example configuration or similar
    if (!$curls) {
      $curls = 1;
      $str .= "\n{{{";
    }
    $str .= "\n# $1";
    next;
  }
  if (/^ *#([^ ].*)$/ || /^ *([^ ].*)$/) {
    # the setting key and default value
    flush_nostr();
    print "\n $1:: ";
    $str = "\n" if ($str eq "");
    flush();
    next;
  }
}
