#! /usr/bin/perl
# aem.pl - by Daniele Raffo, 24/1/2010 - Released under GPL

my $man = "
NAME
       aem.pl - munges email addresses to make them invisible to web spambots

SYNOPSIS
       aem [OPTION] [ADDRESS]...

DESCRIPTION
       This tool munges, i.e. converts char by char to HTML entities, an
       email ADDRESS(es) or any other string fed in input.  The advantage of
       using munged email addresses in web pages is that such munged 
       addresses are invisible to the majority of spambots.  Read
       <http://www.crans.org/~raffo/aem> for more details.

       -h
              show this help and quit

       -i
              interactive mode (ADDRESSes entered as argument are ignored)

       -l
              add a mailto link to the address

       -r
              print also the plain address (useful to distinguish between
              multiple ADDRESSes fed in input)

AUTHOR
       Written by Daniele Raffo.

COPYRIGHT
       Copyright © 2010 Daniele Raffo.  This is free software: you may 
       redistribute copies of it under the terms of the GNU General Public 
       License <http://www.gnu.org/licenses/gpl.html>.
       There is NO WARRANTY, to the extent permitted by law.

";

my $opt_include_link = 0;
my $opt_remember_plain = 0;
my $opt_interactive = 0;
my $opt_show_help = 0;
my @emails;

foreach (@ARGV) {
	if (/^-/) {
		# command-line options
		$opt_include_link = (/.*l.*/);
		$opt_remember_plain = (/.*r.*/);
		$opt_interactive = (/.*i.*/);
		$opt_show_help = (/.*h.*/);
	}
	else {
		# email addresses to mung
		push @emails, $_;
	}
}

if (!@ARGV || $opt_show_help) {
	print $man;
	exit 0;
}

if ($opt_interactive) {
	while () {
		print "Email address to mung, or RETURN to quit: ";
		chomp (my $input = <STDIN>);
		exit 0 if $input =~ /^$/;
		&print_mung ($input);
	}
}
else { &print_mung ($_) foreach (@emails); }



sub mung {
	my @plain = split (//, $_[0]);
	my @munged = (); 
	push @munged, ("&#" . unpack ("C*", $_) . ";") foreach (@plain);
	return @munged;
}



sub print_mung {
	my @address = &mung (@_);
	if ($opt_remember_plain) { print @_, ":\n"; }
	unless ($opt_include_link) { print @address; }
	else { print "<a href=\"&#109;&#97;&#105;&#108;&#116;&#111;&#58;", @address, "\">", @address, "</a>"; }
	print "\n\n";
}

