#!/usr/bin/perl

use v5.20;
use warnings;
use utf8;

use IPC::Run3;
use POSIX qw(strftime);
use Unicode::UTF8 qw(encode_utf8);

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

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

my @command = ('zcat', $man);
my $output;

run3(\@command, \undef, \$output);
my @lines = split(/\n/, $output);

while (defined(my $line = shift @lines)) {
    next
      unless $line =~ /^\.S[SH] HARDWARE CAPABILITIES/i;
    last;
}

while (defined(my $line = shift @lines)) {
    next
      unless $line =~ /^\.B/;
    last;
}

while (defined(my $line = shift @lines)) {

    last
      if $line =~ /^\.S[SH] /;
    next
      if $line =~ /^\./;

    $caps{$_} = 1 for split(/,\s*/, $line);
}

my $path = "$datadir/shared-libs/hwcap-dirs";
my $date = strftime '%Y-%m-%d', gmtime;
open(my $orig, '<', $path)
  or die encode_utf8("Cannot open $path");

while (my $line = <$orig>) {
    chomp $line;

    next
      unless $line =~ m/^#\s*Keep:\s*(.*\S)\s*$/;

    my $keep = $1;
    push @keeps, $keep;

    foreach my $val (split /\s*,\s*/, $keep) {
        $caps{$val} = 1;
    }
}
close($orig);

open(my $fp, '>', $path)
  or die encode_utf8("Cannot open $path");

print {$fp} encode_utf8(<<"EOF");
# List of all known hwcap.
#
# Last updated: $date
# Generated by $0
#
# Lines to always be included:
EOF
foreach my $keep (@keeps) {
    print {$fp} encode_utf8("#    Keep: $keep\n");
}

print {$fp} encode_utf8("\n");

foreach (sort keys %caps) {
    print {$fp} encode_utf8("$_\n");
}
close($fp);

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