#!/usr/bin/perl
# $Id: wle,v 1.1 2000/03/31 22:56:33 dmetz Exp $
# $crtd:  by  Derald Metzger  on  980219 $
# $cmnt:  Extract worklog entries.
#           Copyright (c) 1998 1999  Derald Metzger 
#  This file is part of the cfm pkg (GPL).
# See $usage below for usage info.
# $

$begflg = 0;
$hdrlincnt = 5;
$lincnt = 0;
$nlines = 0;
$prtflg = 0;
@skeys = ();

# Find the default path
$worklogdir=$ENV{WORKLOGDIR} ? "$ENV{WORKLOGDIR}" : "/cm/worklog";
$0 =~ m#wle#o && ($filnam = "$worklogdir/worklog");
$0 =~ m#bbe#o && ($filnam = "$worklogdir/bb");

$usage = "
NAME
  wle   - worklog extraction
  wleh  - worklog extraction from history
  bbe   - bulletin board extraction
  bbeh  - bulletin board extraction from history
SYNOPSIS
  wle  [-f worklog] [-line_cnt] search_key [...]
  wleh [-f worklog] [-line_cnt] search_key [...]
  bbe  [-f worklog] [-line_cnt] search_key [...]
  bbeh [-f worklog] [-line_cnt] search_key [...]
DESCR
  Extracts those item entries whose 1st header line contains the pattern
  \\<search_key>. Escape wildcard chars to protect them from the shell.
  Use ewl or ebb to edit the respective log files.
OPTIONS
  -f worklog  log filename to be searched, default=$filnam
              export WORKLOGDIR to override the default dirname
              -f overrides both the default and WORKLOGDIR
              wleh and bbeh invocations causes .his to be sufixed
  -lincnt     number of lines to extract per entry
              default is the entire entry
  search_key  search key of entries to extract
ALSO
  ewl and ebb are used to edit the respective log files.
  See search_key=format,
  ie execute \`wle|bbe format' for entry format details
";

$arg = shift;

# Get options.
while($arg =~ /^-/) {
   if($arg =~ /^-f/) {$filnam = shift; next;}
   if($arg =~ /-(\d+)$/) {$lincnt = $1; next;}
   die $usage;
}
continue { $arg = shift; }

($arg eq "") && die $usage;

# Adjust worklog name and line based on invocation name
$0 =~ m#wleh|bbeh#o && ($filnam = $filnam . '.his');
$lincnt || $0 =~ m#wles#o && ($lincnt = $hdrlincnt);
$lincnt || $0 =~ m#wlehs#o && ($lincnt = $hdrlincnt);

@skeys = ($arg, @ARGV);

for $skey (@skeys) {
   open(WORKLOG, $filnam) || die "Cant open file $filnam: $!\n";
   while(<WORKLOG>) {
      if($begflg && /^\\/ && /\\$skey/i) {
         $begflg=0; $nlines=0; $prtflg=1; print "\n";}
      if(/^\n/) {
         $begflg=1; $prtflg=0; next;}
      if(! $prtflg) {
         next;}
      if($lincnt && ($nlines >= $lincnt)) {
         $prtflg=0; next;}
      print; $nlines++;
   }
   close(WORKLOG);
}

exit 0;
