#!/usr/bin/env perl

use strict;

my($label) = "spammer's hosts";
my($label) = ""; # если не указана метка, то пересортировуется весь поток

my(@part1, %helo, %part2, @part3, $action, $mailbox, $domain, $sub_domain, $remark);

while (<>) {
    push(@part1, $_) if ((1 .. /$label \(begin\)/i) && ($label));
    if ((/$label \(begin\)/i .. /$label \(end\)/i) || (!$label)) {
#print("!!!1 $_") if (/spam:/i);
	if ((!/^[\n\r]/) && ((! /$label/i) || (!$label))) {
#print("!!!2 $_") if (/spam:/i);
	    if (/^([#\s]*helo:)(\S+)/i) {
		$helo{lc($2)."\thello"} = $_;
	    } else {
		$mailbox =undef;
		$domain = undef;
		if (/^[#\s]*\S+\@/) {
		    ($remark, $action, $mailbox, $domain) = (/^(#\s*)*(spam:|connect:|from:|to:)?(\S+)\@(\S+)*\s+/i);
		} else {
		    ($remark, $action, $domain) = (/^(#\s*)*(spam:|connect:|from:|to:)?(\S+)\s+/);
		}
#print("!!!3 $action: $_") if (/spam:/i);
		$domain =~ tr/A-Z/a-z/;
		$mailbox =~ tr/A-Z/a-z/;
		my(@sub_domains) = split(/\./, $domain);
		if ((!$mailbox) && ($domain =~ /\d+\.\d+\.\d+\.\d+/)) {
		    $domain = ' ';
		    while ($sub_domain = shift(@sub_domains)) {
			$domain	.= sprintf("%03d.", $sub_domain);
		    }
		} else {
		    $domain = '';
		    while ($sub_domain = pop(@sub_domains)) {
			$domain	.= "$sub_domain.";
		    }
		}
#print("!!! $_") if ($action =~ /spam/i);
		$part2{"$domain\t$mailbox\t$action"} = $_;
	    }
	}
    }
    push(@part3, $_) if ((/$label \(end\)/i .. eof()) && ($label));;
}

print(@part1);
print("\n");
foreach (sort(keys(%helo))) {
	print($helo{$_});
}
print("\n");
foreach (sort(keys(%part2))) {
	print($part2{$_});
}
print("\n");
print(@part3);
