#! /usr/bin/perl
use warnings;
use strict;
use integer;
use bytes;
use FindBin;
use lib $FindBin::RealBin;
use Def;

# This script searches certain fields of a Packages file for a pattern.
# If it finds the pattern, then it prints the corresponding line from a
# debram.txt body.

our %field = map { $_=>1 } qw(
  Package
  Source
  Provides
  Pre-Depends
  Depends
  Recommends
  Description
);

our $usage = <<END;
usage: $0 [-hx] [Packages file] [pattern] [debram.txt body]
    -h print this usage message
    -x suppress empty rams
END

# Read command-line arguments and options.
my @opt;
my @arg;
{
  my $stopopt = '';
  for ( @ARGV ) {
    if    ( $stopopt  ) { push @arg, $_        }
    elsif ( $_ eq '-' ) { $stopopt = '1'       }
    else  { push @{ /^-/ ? \@opt : \@arg }, $_ }
  }
}
my %opt = map { my @o = split ''; shift @o; map {$_=>1} @o; } @opt;
if ( $opt{'?'} || $opt{h} || @arg != 3 ) { print $usage; exit 0; }
my( $fn_packages, $pat, $fn_body ) = @arg;

my $w0 = $Def::w_maint + $Def::w_pri;
my $w3 = $w0 - 3;

my %p;

# Scan the Packages file.
{
  local $/ = '';
  open  P, '<', $fn_packages;
    while (<P>) {
      my( $name ) = /^Package: (\S+)/m
        or die "$0: cannot determine the package name of\n$_\n";
      for ( /^.*$/mg ) {
        my( $key, $text ) = /^(\S+):(.*)$/ or next;
        $field{$key} or next;
        $p{$name} = 1 if $text =~ /$pat/;
      }
    }
  close P;
}

# Filter the debram.txt body to stdout.
{
  my $out     = '';
  my $doprint = '';
  open  D, '<', $fn_body;
    while (<D>) {
      if    ( !/^\S/ ) {
        $out    .= $_;
        print $out if $doprint || !$opt{x};
        $out     = '';
        $doprint = '';
      }
      else {
        my( $name ) = /^.{$w3} \267 (\S+)/;
        if ( defined $name ) {
          if ( $p{$name} ) {
            $out    .= $_ ;
            $doprint = '1';
          }
        }
        else {
          $out .= $_;
        }
      }
    }
  close D;
  print $out if $doprint || !$opt{x};
}

# Here are some interesting patterns to feed to the script:
# \b(?:perl(?:api)?\d*)\b
# \bpy|python
# ruby
# \b(?:lib)?(?:i|pl)?(?:tcl|tk)|expect|wish
# \b(?:lib(?:atk|bonobo\w*|cairo|gconf|gdk|gl|glade|glu|gnome\w*|gtk|ice|pango|qt|sdl|sm|x|xaw|xcursor|xext|xfixes|xft|xi|xinerama|xmu|xpm|xrandr|xrender|xt)|gconf|gdk|kdelibs|tcl|tk|x11|xfonts|xlibmesa|xlibs)\d*\b
# \b(?:lib(?:bonobo\w*|gconf|gnome\w*)|gconf)\d*\b
# libkde|kdelibs

