#!/usr/bin/perl -w
#
# Description: generating a manpage from help output
#
# Copyright © 2009 Mehdi Dogguy <dogguy@pps.jussieu.fr>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA.
#

my $command = $ARGV[0] || "mlnet";
my $option = "";
my $desc = "";

open (HELP, "< $command.help") || die("Cannot find $command.help\n");
open (XML , "< $command.tpl.xml") || die("Cannot find $command.tpl.xml\n");
open (NEW , "> $command.xml");

sub clean() {
    my $expr = shift;
    $expr =~ s/</&lt;/g;
    $expr =~ s/>/&gt;/g;
    $expr =~ s/\n//g;
    return $expr;
}

sub print_item() {
    my $opt = shift;
    my $des = shift;
    if ($opt ne "") {
	$opt =~ s/</&lt;/g;
	$opt =~ s/>/&gt;/g;

	print NEW "\t<varlistentry>\n";
	print NEW "\t\t<term><option>$opt</option></term>\n";
	print NEW "\t\t<listitem>\n$des\t\t</listitem>\n";
	print NEW "\t</varlistentry>\n";
    }
}

while (<XML>) {
    if (/\@GENERATE_MAN\@/) {
	while (<HELP>) {
	    if (/^  (-[^:]*[a-zA-Z>"])([ ]*:[ \t]+(.*)[ ]*$)?/) {
		&print_item($option, $desc);
		$option = "$1";
		$desc = "";
		if (defined $2) {
		    if ($3 =~ /private key/) {
			$desc .= "\t\t\t<para>The RSA private key of this client</para>\n";
		    } elsif ($3 ne "") {
			$desc .= "\t\t\t<para>".&clean($3)."</para>\n";
		    }
		}
	    } elsif (/([^ ].*)\n/) {
		$desc .= "\t\t\t<para>".&clean($1)."</para>\n";
	    }
	}
	&print_item($option, $desc);
    } else {
	print NEW;
    }
}
