#!/usr/bin/perl
# $Id: decode_teergrube.pl 44 2003-02-01 22:56:20Z aqua $
#
# Decodes teergrube-bait addresses emitted by sugarplum.  Addresses will be
# decoded either from the commandline or stdin.
#

grep($_ eq '-h',@ARGV) and do {
	print "usage: $0 addr1 addr2 ...\n",
		"Run without arguments, accepts a list of addresses on stdin,",
		" one per line.\n";
	exit;
};

if (@ARGV) {
	for (@ARGV) {
		print &decode_teergrube_address($_) || 'not a teergrube address',
			"\n";
	}
	exit;
}

while (<>) {
	chomp;
	print &decode_teergrube_address($_) || 'not a teergrube address',"\n";
}


sub decode_teergrube_address {
        my $uname = shift || return undef; $uname = lc $uname;
        $uname =~ /^([a-z])([a-z])([a-z]{8,})/ or return undef;
        my $permutation = ((ord($1)-97)<<4) | ord($2)-97;
        $uname = $3;
        my @addr;

        for (0..7) {
                if ($permutation & 1<<$_) {
                        $uname = substr($uname,0,$_).substr($uname,$_+1);
                }
        }
        @addr = ();
        for (0..3) {
                push @addr, ((ord(substr($uname,$_,1))-97<<4) |
                                (ord(substr($uname,$_+4,1))-97));
        }
        wantarray and return @addr;
        join('.',@addr);
}

