#!/usr/bin/perl

use strict;
use warnings;

use POSIX qw(strftime);

my $datadir = shift;
my $man = shift // '/usr/share/man/man8/ld.so.8.gz';
my %caps;
my @keeps = ();

die "Usage: $0 path/to/lintian/data.\n" unless $datadir;

open my $manpage, '-|', 'zcat', $man or die "zcat $man: $!";
while (<$manpage>) {
    next unless /^\.SH HARDWARE CAPABILITIES/;
    last;
}
while (<$manpage>) {
    next unless /^\.B/;
    last;
}
while (<$manpage>) {
    last if /^\.SH /;
    next if /^\./;
    chomp;
    $caps{$_} = 1 foreach split /,\s*/;
}
close $manpage or die "zcat: $!";

my $path = "$datadir/shared-libs/hwcap-dirs";
my $date = strftime '%Y-%m-%d', gmtime;
open my $orig, '<', $path or die "Opening $path: $!";
while ( my $line = <$orig> ) {
    chomp $line;
    next unless $line =~ m/^#\s*Keep:\s*(.*\S)\s*$/o;
    my $keep = $1;
    push @keeps, $keep;
    foreach my $val (split /\s*,\s*/o, $keep) {
        $caps{$val} = 1;
    }
}
close $orig;

open my $fp, '>', $path or die "Opening $path: $!";
print $fp <<EOF ;
# List of all known hwcap.
#
# Last updated: $date
# Generated by $0
#
# Lines to always be included:
EOF
foreach my $keep (@keeps) {
    print $fp "#    Keep: $keep\n";
}

print $fp "\n";

foreach (sort keys %caps) {
    print $fp "$_\n";
}
close $fp or die "Closing $path: $!";

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