#!/usr/bin/perl

########################################################
#
# spamnames.cgi by greenfly <greenfly@greenfly.org>
# 
# This CGI chooses names taken by grepping my spam
# Maildir with the following command:
# $ egrep -ih "^FROM:" Maildir/.spam/cur/* > spamnames.txt
#
# The spamnames file is then processed to strip 
# first and last names from the file, and then 
# randomly display them.
#
########################################################


use strict;
use CGI qw(:standard);

our $namefile = "spamnames.txt";
my %names; 
my @first_names;
my @last_names;

%names = grab_names();

@first_names = keys %{ $names{first} };
@last_names = keys %{ $names{last} };

print "Content-type: text/html\n\n";
print "<html><head><title>Spam Name Generator</title></head>\n";
print "<body>\n";
print "<form method=\"post\" action=\"/spamnames.cgi\">\n";

print "<input type=\"submit\" value=\"Generate a New Name\" name=\"submit\">\n";
if(param())
{
print "<p>Your name is <b>$first_names[rand($#first_names)] $last_names[rand($#last_names)]\n";
   print "</b><br /><br />\n";
}
print "</form>";
print "</body></html>";


sub grab_names
{
   my $full_name;
   my $first_name;
   my $last_name;
   my %names;

   open INFILE, "$namefile";

   while(<INFILE>)
   {
      /From: \"?([^"]*)\"?\s?\<?/;
      $full_name = $1;

# now clean up the name
      $full_name =~ s/<.*$//g;
      $full_name =~ s/^(\w+) \w\.? (\w+)/$1 $2/;
      $full_name =~ s/\@[^ ]+//g;
      $full_name =~ s/^(Dr|M(r|rs|s|iss|z))\.?\s?//i;
      $full_name =~ s/\.\S*//;
      $full_name =~ s/[^A-Za-z ]//g;

      ($first_name, $last_name) = split " +", $full_name;
# capitalize the name
      $first_name =~ s/(\w+)/\u\L$1/;
      $last_name =~ s/(\w+)/\u\L$1/;

# add the name as long as it's longer than a single character
      $names{first}{$first_name} = 1 unless($first_name =~ /^\w{0,1}$/);
      $names{last}{$last_name} = 1 unless($last_name =~ /^\w{0,1}$/);
   }
   return %names;
}
