#!/usr/bin/perl -w

use strict;
use warnings;

use Getopt::Long;
#use File::Basename;

my $verbose=0;
my $help=0;

my $result = GetOptions (
    'quiet'=> sub {$verbose=0},
    "verbose+"  => \$verbose,
    "help"  => \$help,
);

my %HINTS;

while (<>) {
    my ($pkgid,$file,$srcid,$pkgname)=split(/\s+/,$_);
    next unless $srcid; # empty line ?
    my $key=$srcid.':'.$pkgname;
    if (!defined($HINTS{$key})) {
	&load_hints($key,$srcid,$pkgname);
    }
    my $match=0;
    if ($HINTS{$key}) {
	# altlinux-python-test-is-packaged!!!
	$file=~s!^/usr/(?:lib|lib64|share)/python[\d.]+/site-packages/!!;
	foreach my $pattern (@{$HINTS{$key}}) {
	    #warn "for $file: trying pattern: $pattern\n";
	    if ($file=~/$pattern/){
		$match=1;
		#warn "hint: excluded $file by $pattern\n";
	    }
	}
    }
    print $_ unless $match;
}

sub load_hints {
    my ($key,$srcid,$pkgname)=@_;
    $HINTS{$key}=0;
    my $hintfile=$ENV{'REPOCOP_STATEDIR'}.'/repocop-hint/'.$srcid.'/repocop-test-hint:binary:'.$pkgname.':altlinux-python-test-is-packaged';
    return unless -e $hintfile;
    #warn "found hint file $hintfile\n";
    open (my $fn,'<',$hintfile)|| die "Oops: opening $hintfile: $!";
    my $glob;
    my @patterns;
    while ($glob=<$fn>) {
	chomp $glob;
	next if /^\s*$/;
	next if /^\s*#/;
	push @patterns, &glob2pat($glob);
    }
    close($fn);
    $HINTS{$key}=\@patterns;
}

sub glob2pat {
    my $globstr = shift;
    my %patmap = (
	'*' => '.*',
	'?' => '.',
	'[' => '[',
	']' => ']',
	'{' => '(?:',
	'}' => ')',
	',' => '|',
	);
    $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
    return '^' . $globstr . '$';
}

