#!/usr/bin/perl
# filter of help2man output
use strict;
use warnings;
use Dpkg::Changelog::Parse;

# parse changelog for version
my $version;
my %opt;
$opt{file} = "debian/changelog";
my @fields = changelog_parse(%opt);
foreach my $f (@fields) {
    $version = $f->{Version} if exists $f->{Version};
    #strip debian revision
    $version =~ s/(.*)-1$/$1/;
}

while ( <STDIN> ) {
    #multiline regex
    undef $/;
    # remove colon from the name
    s/(\.TH\s([\w\d-]*)):/$1/gmxs;
    # substitude unrecognized version string with the version
    s/([\w\d]*)\:\sunrecognized\soption\s\'--version\'/$1 $version/g;
    s/([\w\d]*)\:\sunrecognized\soption\s\'\\-\\-version\'/ $version/g;
    # there are no invalid options
    s/([\w\d]*)\:\sinvalid\soption\s--\s\'-\'/$1 $version/g;
    # strip the header or duplicated body of coverageCount
    s/\.SH\s(DESCRIPTION|SYNOPSIS).*(Usage:\"?|genome\.\n\.PP)/.SH USAGE\n/gmxs;
    # strip full path
    s/\\fI\\,\/.*\/bin(\/utilities)?\///gmxs;
    # tidy up help2man removeDuP output:
    s/Repeated\sRead\sRemoval.*accessible:\s\'\'//xms;
    s/(.SH\sNAME\n[\w\d-]*):/$1/gxms;
    # remove "./" from examples
    s/(\\\&\.\/)([\w\d-]*)/$2/gxms;
    # remove indent and "boldify" the name
    s/(\.SH\sUSAGE\n*)(\.IP\n|\s|\.TP\n)([\w\d\\-]*)/$1\\fB$3\\fR/xms;
    s/removeDup\\\\fR\/\\fP/removeDup\\fR/gmxs;
    print;
}
