#!/usr/bin/perl -w
# $Id$
#use strict;

($C = $0) =~ s%.*/%%;

my $Mode = "files";
my $Append = "";
my $Help = 0;
my $OptErr = "";
my $debug = 0;


while ( $#ARGV >= $[ && ($_ = shift, /^-/) ) {
  last if /^--$/;
  (/^--dirs$/ || /^-d$/)		&& ($Mode = "dirs", next);
  (/^--files$/ || /^-f$/)		&& ($Mode = "files", next);
  (/^--append$/ || /^-a$/)		&& ($Append = ">", next);
  (/^--debug$/ || /^-d$/)		&& ($debug ++, next);
  (/^--?help/ || /^-h/)			&& ($Help = 1, next);
  (/^-/)				&& ($OptErr .= "$_ ", $_ = "", next);
}

if ( $OptErr ) {
  printf( STDERR "$C: unkown option: $OptErr\n");
}

my $Pkg = $_;

if ( $OptErr || $Help || ! defined($Pkg) || ! -r "$Mode-$Pkg" ) {
  die( "Usage: $C [-a] [-d] pkg-name\n");
}

my @default =
  ( $Mode eq "files" ) ? (
	    [ '/man/man[1456789n]/',		"base"],
	    [ '/man/man[23]/',			"devel"],
	    [ '^/usr/include',			"devel"],
	    [ '^(/usr)?/lib/.*\.so',		"devel"],
	    [ '^(/usr)?/lib/.*\.a',		"devel-static"],
	    [ '^\s*$',					"IGNORED"],
	    [ '^#$',					"IGNORED"],
	    [ '.*',				"base"],
  ) : (
	    [ '^/(bin|dev|etc|lib|sbin|usr|var)/$',	"IGNORED"],
	    [ '^/usr/(bin|doc|include|lib|man|sbin)/$',	"IGNORED"],
	    [ '^/usr/doc/',				"IGNORED"],
	    [ '^/usr/man/man[123456789n]/$',		"IGNORED"],
	    [ '^/var/(lib|run|state)/$',		"IGNORED"],
	    [ '.*',				"base"],
  );

if ( $Mode eq "dirs" ) {
  $Prefix = "%dir ";
} else {
  $Prefix = "";
}

my $i;
my @f2p = ();
my %subs = ();

unshift(@ARGV, '-') if $#ARGV < $[;
while ( <> ) {
  next if ( m:^\s*$: || m:^\s*\#: );
  print( STDERR "processing") if ( $debug );
  if ( m:^\@default: ) {
    print( STDERR " defaults...\n") if ( $debug );
    for ( $i = 0 ; $i <= $#default ; $i ++ ) {
      push @f2p, [ @{$default[$i]} ];
    }
  } else {
    print( STDERR " rule...\n") if ( $debug );
    push @f2p, [ split ];
  }    
}

for $i ( 0 .. $#f2p ) {
  printf( STDERR "pkg='%s' pattern='%s'\n", $f2p[$i][1], $f2p[$i][0])
     if ( $debug );
  $subs{$f2p[$i][1]} ++;
}

open( IN, "< $Mode-$Pkg" ) || die( "open('$Pkg'): $!\n");
foreach $i ( (sort( keys( %subs)), "IGNORED") ) {
  printf( STDERR "sub='%s': %d\n", $i, $subs{$i}) if ( $debug >= 5 );
  open( $i, ">$Append files-$Pkg-$i") || die( "open('$Pkg-$i'): $!\n");
}

while ( <IN> ) {
  my $out = match( $_ );
  printf( STDERR "%-20s %s", "$out:", $_) if ( $debug >= 1 );
  print( $out $Prefix . $_);
}

foreach $i ( (sort( keys( %subs)), "IGNORED") ) {
  close( $i);
  if ( -z "files-$Pkg-$i" ) {
    printf( STDERR "removing empty '%s'\n", "files-$Pkg-$i") if ( $debug >= 1 );
    unlink( "files-$Pkg-$i");
  }
}
close( IN);

exit( 0);

sub match($) {
  my ( $t) = @_;
  my ( $i) = 0;

  while ( $i <= $#f2p ) {
    my $p = $f2p[$i][0];
    printf( STDERR "testing(%d): '%s'\n", $i, $p) if ( $debug >= 99 );
    last if ( $t =~ m:$p: );
    $i ++;
  }
  return ( (defined( $f2p[$i])) ? $f2p[$i][1] : "IGNORED" );
}

