#!/usr/bin/perl -w
# ar-info -- lintian collection script
#
# Copyright © 2009 Stéphane Glondu
# Copyright © 2019 Felix Lechner
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, you can find it on the World Wide
# Web at http://www.gnu.org/copyleft/gpl.html, or write to the Free
# Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
# MA 02110-1301, USA.

package Lintian::coll::ar_info;

no lib '.';

use strict;
use warnings;
use autodie;

use lib "$ENV{LINTIAN_ROOT}/lib";

use Path::Tiny;

use Lintian::Collect::Dispatcher qw(create_info);
use Lintian::Util qw(safe_qx);

use constant EMPTY => q{};
use constant SPACE => q{ };
use constant COLON => q{:};
use constant NEWLINE => qq{\n};

sub collect {
    my ($pkg, $type, $dir) = @_;
    my $info;

    my $basket = "$dir/ar-info";

    unlink($basket)
      if -e $basket;

    # stop here if we are only removing the files
    return
      if $type =~ m/^remove-/;

    $info = create_info($pkg, $type, $dir);

    chdir("$dir/unpacked");

    my @archives;
    foreach my $file ($info->installed->sorted_list) {
        next unless $file->is_regular_file && $file =~ m{ \. a \Z }xsm;

        # skip empty archives to avoid ar error message; happens in tests
        next unless $file->size;

    # fails silently for non-ar files (#934899); probably creates empty entries
    # in case of trouble, please try: "next if $?;" underneath it
        my $output = safe_qx('ar', 't', $file);
        my @contents = split(/\n/, $output);

        my $line = $file . COLON;
        $line .= SPACE . $_ for @contents;
        push(@archives, $line);
    }

    my $string = EMPTY;
    $string .= $_ . NEWLINE for @archives;
    path($basket)->spew($string);

    return;
}

collect(@ARGV) unless caller;

1;

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