#!/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 $_;
}
