#!/usr/bin/perl -w
# strings -- lintian collection script

# Copyright © 2009, 2010 Raphael Geissert <atomo64@gmail.com>
# 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::strings;

no lib '.';

use strict;
use warnings;
use autodie;

use Path::Tiny;

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

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

use constant DOT => q{.};
use constant GZ => q{gz};

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

    my $stringdir = "$dir/strings";
    path($stringdir)->remove_tree
      if -d $stringdir;

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

    # the directory is required, even if it stays empty.
    path($stringdir)->mkpath
      unless -e $stringdir;

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

    foreach my $file ($info->installed->sorted_list) {

        next
          unless $file->is_file;

        next
          if $file->name =~ m,^usr/lib/debug/,;

        # skip non-binaries
        next
          unless $info->file_info($file->name) =~ m/\bELF\b/o;

        # prior implementations sometimes made the list unique
        my $allstrings = safe_qx('strings', '--all', '--',$file->fs_path);

        # calculate destination path
        my $relative = $file->name . DOT . GZ;
        my $zippath = path($relative)->absolute($stringdir)->stringify;

        # make sure destination folder exists
        path($zippath)->parent->mkpath
          unless path($zippath)->parent->exists;

        # write file
        gzip($allstrings, $zippath);
    }

    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
