#!/usr/bin/perl

use strict;
use warnings;

# Find the lib directory of lintian-root (defaulting to ./lib/)
BEGIN {
    $ENV{LINTIAN_ROOT} //= '.';
}
use lib $ENV{LINTIAN_ROOT} . '/lib/';

use Lintian::Util qw(read_dpkg_control fail);

my @keywords = ();

foreach my $kw (qw(conffiles shlibs Standards-Version)){
    push @keywords, [qr/$kw/, "B<$kw>"];
}

open my $file, '<', 'man/lintian.pod.in' or fail "man/lintian.pod.in: $!";

while(my $line = <$file>){
    chomp($line);
    if($line eq '@CHECKS@'){
        extract_data ('checks', 'check-script', 'abbrev');
    } elsif($line eq '@COLLECTION@'){
        extract_data ('collection', 'collector-script');
    } else {
        print "$line\n";
    }
}
close $file;

sub pretty_print {
    my $text = shift;
    my $inex = 0;
    $text =~ s@\n\s\.\n\s@\n\n\n@og;
    $text =~ s@\n\s@\n@og;
    $text =~ s/\&([^;]+)\;/E<$1>/og;  # do &gt; -> E<gt>
    $text =~ s/(\S+\(\d+\))/L<$1>/og; # link to manpages
    foreach my $line (split /\n/o, $text) {
        if($line =~ m/^ /o){
            if(!$inex){
                # Start of an example.
                $inex = 1;
                # Give an extra line break.
                $line = "\n$line";
            }
            # Example line
            print "$line\n";
            next;
        } elsif($inex) {
            # First line after an example.
            $inex = 0;
            $line = "\n\n$line";
        }
        # Normal line
        # Replace simple html tags
        $line =~ s@\<tt\>([^<]*)\</tt\>@I<$1>@iog;
        $line =~ s@\<b\>([^<]*)\</b\>@B<$1>@iog;
        $line =~ s@\<i\>([^<]*)\</i\>@I<$1>@iog;
        # Underline paths
        $line =~ s@(\S*/(?:[^/ \t]++/?)*)@I<$1>@og;
        # Policy Manual
        $line =~ s@Policy Manual@B<Policy Manual>@og;
        foreach my $kw (@keywords){
            my ($s,$r) = @$kw;
            $line =~ s|\b\Q$s\E\b|$r|;
        }
        print "$line\n";
    }
    print "\n\n";
}

sub extract_data {
    my ($folder, $fname, $abname) = @_;
    print "=over 4\n\n";
    foreach my $file (<$folder/*.desc>) {
        my ($header, @ignore) = read_dpkg_control ($file);
        my $name = $header->{$fname};
        my $abbr;
        my $desc;
        next if $name eq 'lintian';
        if (defined $abname) {
            $abbr = $header->{$abname};
        }
        if (!defined $header->{'manpage'}) {
            $desc = $header->{'info'};
        } else {
            $desc = $header->{'manpage'};
        }
        if ($abbr) {
            print "=item B<$name> (B<$abbr>)\n\n";
        } else {
            print "=item B<$name>\n\n"
        }
        pretty_print($desc);
        if (lc ($header->{'auto-remove'}//'') eq 'yes') {
            print "This collection is auto-removed by default in static labs.\n\n"
        }
    }
    print "=back\n\n";
}

# Local Variables:
# indent-tabs-mode: nil
# cperl-indent-level: 4
# End:
# vim: syntax=perl sw=4 sts=4 sr et
