#!/usr/bin/perl

use strict;
use vars qw { $USER $IS_SPAM @buffer $line $file };

# dspam_corpus: small tool to automatically add a corpus of mail to a dictionary

# Syntax: dspam_corpus [username] [filename] [--addspam]
#  Flags: --addspam corpus is known spam

sub DSPAM_BINARY { '/usr/bin/dspam'; }

my($USER) = shift;
$file = shift;

if ($USER eq "" || $file eq "") {
  print "Syntax: $0 [user] [filename] [--addspam]\n";
  exit;
}
 
$line = 0;

my($IS_SPAM) = shift;

open(FILE, "<$file") || die "$file: $!";
while(<FILE>) {
  if (/^From / && $line>0) {
    call_dspam();
  } 
  push(@buffer, $_);
  $line++;
}

call_dspam();
close(FILE);

sub call_dspam {
  printf("Calling DSPAM (%s)...\n", DSPAM_BINARY);
  open(PIPE, "|'".DSPAM_BINARY."' --corpus --user '$USER' -d '$USER' $IS_SPAM") || die $!;
  foreach(@buffer) {
    print PIPE $_;
  }
  close(PIPE);
  @buffer = ( );
}
