#!/usr/bin/perl -w

# Usage: unsub2sql.pl <txtlist> <sqlout> 
#
# Example:  unsub2sql.pl unsubs.21Dec06.do unsubs.21Dec06.sql 
#
# David Harris, Version of 21 Dec 2006 00:00 GMT

# ------------------------------------------------

# Check the number of arguments on the command line:
if ($#ARGV+1 != 2) {
  die "unsub2sql.pl needs <txtlist> <sqlout> as arguments";
};
# Check existence of the textfile and email listing file:
(open TXTLIST, "<$ARGV[0]") or die "unsub2sql.pl txtlist file $ARGV[0] not found.\n";
(open SQLOUT, ">$ARGV[1]") or die "unsub2sql.pl SQL file not made.\n";
$tablename = "unsubscribers";
#Read through TXTLIST file:
while ($lineread = <TXTLIST>) {
  chomp $lineread;
  $email = $lineread;
  $email =~ s/'/\\'/g;  #Deal with O'Connor etc.
  $email =~ s/"//g;  #Deal with quotes around names.
  $email =~ tr/A-Z/a-z/;  #LOWERCASE all letters in emails
  $email =~
    s/^\s*([a-zA-Z0-9_\-]+@[a-zA-Z0-9_\-\.]+)\s*/$1/ ; #Remove WHITESPACE
  # The format of the SQL INSERT line: 
  print SQLOUT "INSERT INTO `$tablename` (`email`) VALUES (\'$email\');\n" ;

}
close SQLOUT;
close TXTLIST;
exit;