#!/usr/athena/bin/perl

$quiet = 0;
if (@ARGV && $ARGV[0] eq '-q')
{
  shift @ARGV;
  $quiet = 1;
}

$pgm='inc';
$pgm = join(' ',@ARGV) if @ARGV;

$user = ($ENV{ "USER" } || (getpwuid($<))[0]);
$homedir = ($ENV{ "MAILHOME" } || $ENV{ "HOME" } || "/mit/$user");
$listfile = "$homedir/Mail/lists";

open( INC, "$pgm -format '%(msg)|%{to}|%{apparently-to}|%{cc}|%{from}|%{subject}' -width 999 |" );

open( LISTS, $listfile );
$_ = <LISTS>;
chop;
@me = split;
@lists = <LISTS>;
close( LISTS );

while( <INC> )
{
  $fields = ( ($num,$to,$apto,$cc,$from,$subject)=split(/\|/) );
  print if $fields > 6;
  next if $fields != 6;
  @all=();
  @recips=();
  $me=0;
  for $i ( split(',',$to), split(',',$apto), split(',',$cc) )
  {
    $i =~ s/"[^"]*"//;
    $i =~ s/\([^)]*\)//;
    $i = $1 if $i =~ /<([^>]+)>/;
    $i =~ s/^\s*//;
    $i =~ s/\s*$//;
    $i =~ s/[.@]pch\.mit\.edu$//i;
    $i =~ s/[.@]mit\.edu$//i;
    $i =~ s/\@[a-zA-Z-]+\.lcs$/\@lcs/i;
    push( @all, $i );
    $s = $i;
    $s =~ s/(\W)/\\$1/g;
    push( @recips, $i ) if grep(/^$s$/i, @lists);
    $me = 1 if !@recips && !$me && grep(/^$s$/i, @me);
  }
  if (@recips)
  {
    $to = join(', ',@recips);
    $flag = '';
  }
  else
  {
    if ( $from =~ /"([^"]+)"/ )      { $from = $1; }
    elsif ( $from =~ /\(([^)]+)\)/ ) { $from = $1; }
    else
    {
      $from =~ s/<[^>]+>//;
      $from =~ s/^\s*//;
      $from =~ s/\s*$//;
      $from =~ s/[.@]mit\.edu$//i;
    }
    $to = $from;
    $flag = ' -';
    if (! $me)
    {
      print "recipient not found in: ".join(',',@all)."\n" if ! $quiet;
      $flag = ' ?';
    }
  }
  write;
}

close( INC );
exit;

format STDOUT =
@####@< @<<<<<<<<<<<<<<<<<<<<<<<< @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$num,$flag,$to,                   $subject
.
