#!/usr/bin/perl -w

###########################################################################
### $Id: //depot/personal/ryan/main/src/wham/bin/add_white#2 $
###########################################################################
###
###########################################################################

use FindBin '$RealBin';                             # locate libraries
BEGIN { unshift(@INC,"$RealBin/../lib") }

use strict;
use Getopt::Long;
use wham;
use Mail::Field::AddrList;

my( %argv, $line, $filter, %config, @WHITE, $addr, @addrs);

### Get options
if( !(GetOptions( \%argv, "a|address=s", "m|comment=s", "c|config=s", 
		  "v|verbose", "h|help","g")) || defined($argv{h})) {
	print STDERR "Usage: spammail [options]\n";
	print STDERR "options\n";
	print STDERR " -a, --address <addrs>     addresses to add\n";
	print STDERR " -c, --config <file>       path to config file\n";
	print STDERR " -m, --comment <comment>   comment to put into whitelist\n";
	print STDERR " -g, --grok                grok From address in the email headers on stdin\n";
	exit 0;
}

### Where is the config file
%config = &LoadConfig($argv{c});

### Get the addrs from the cmd line if specified or from stdin
if( defined( $argv{"a"}))
{
	@addrs = split( /,/, $argv{"a"});
} elsif( defined( $argv{g})) {
  @addrs = &GrokMessage( \*STDIN);
  foreach $addr (@addrs) {
    print "$addr\n";
  }
} else {
	@addrs = <>;
}

### Load in the white and white lists
@WHITE = &ReadList( $config{white});

foreach $addr (@addrs)
{
  #	print "--->$addr\n";
  ### Anything that matches WHITE filters is trusted
  foreach $filter (@WHITE) {
    print STDERR "INFO =~ white '$filter'\n" if( defined( $argv{"v"}));
    if( $addr =~ /$filter/i) {
      print STDERR "$addr is covered by whitelist rule '$filter'\n";
      exit 1;
    }
  }
}

if( ($addr = &AddToList( "white", $argv{m}, @addrs)) ne "") {
	print STDERR $addr, "\n";
	exit 1;
}


