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

# Copyright (C) 2012 Niels Thykier <niels@thykier.net>
#
# 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.

use strict;
use warnings;
use autodie;

use File::Basename qw(dirname);
use IO::Handle;

use lib "$ENV{'LINTIAN_ROOT'}/lib";
use Lintian::Command qw(spawn reap);

my ($strdir) = @ARGV;
my $curfname = '';
my $curdir = '';

my %seen;
my %opts = (fail => 'error');
my $out = undef;

while (my $line = <STDIN>) {
    my ($fname, $string);
    chomp $line;
    ($fname, $string) = ($line =~ m/^([^:]++): (.++)$/o);
    if ($curfname ne $fname) {
        # new file, prepare for it.
        if ($out) {
            close($out);
            reap(\%opts);
            undef(%seen);
        }
        my $dir = $strdir . '/' . dirname($fname);
        if ($dir ne $curdir) {
            system('mkdir', '-p', $dir) == 0
              or die "mkdir -p $dir failed: " . (($? >> 8) & 256), "\n";
            $curdir = $dir;
        }
        $opts{out} = "$strdir/${fname}.gz";
        $out = $opts{pipe_in} = IO::Handle->new;
        spawn(\%opts, ['gzip', '-9nc']);
        $opts{pipe_in}->blocking(1);

        $curfname = $fname;
    }
    next if $seen{$string}++;
    print {$out} "$string\n";
}

if ($out) {
    close($out);
    reap(\%opts);
}

exit 0;
