#!/usr/bin/env perl

use strict;
use warnings;
use Regexp::IPv6 qw($IPv6_re);

my $command = "dnstwist --ssdeep --registered --mxcheck --geoip --banners debian.org";

open(DNSTWIST, $command . " |") || die("Problem opening file\n");

my $log = "\$ " . $command . "\n";
my @problematic_lines;

# Look for problems in dnstwist output
while (<DNSTWIST>) {
	my $line_prefix = "Line " . $. . ": "; # prefix line number for simpler debugging
	my $line = $_;
	$log .= $line;
	next if $. < 7; # skip logo lines

	if ($. == 7) {
		push @problematic_lines, $line_prefix . $line
		  unless (/^Fetching\scontent\sfrom:\shttp(s)?:\/\/debian\.org\s200\sOK\s\(\d+(\.\d+)?\s[KMGT]?bytes\)$/);
	}
	elsif ($. == 8) {
		push @problematic_lines, $line_prefix . $line
		  unless (/^Processing\s\d+\spermutations\s[·.0-9%]+\s\d+\shits/);
	}
	elsif ($. == 10) {
		push @problematic_lines, $line_prefix . $line
		  unless (/^original\*\s+debian\.org\s+([0-9]{1,3}\.){3}[0-9]{1,3}\/.+\s$IPv6_re\sNS:\S+\sMX:\S+\sHTTP:".+"$/);
	}
	elsif ($. > 10) {
		push @problematic_lines, $line_prefix . $line
		  unless (/^(addition|bitsquatting|homoglyph|hyphenation|insertion|omission|repetition|replacement|subdomain|transposition|vowel-swap|various)\s+\S+\s+((([0-9]{1,3}\.){3}[0-9]{1,3}\/.+)|(!ServFail\s(!ServFail\s)?))?(NS:\S+)?(\sMX:\S+)?(\sHTTP:".+")?(\sSMTP:".+")?(\sSSDEEP:\d+\%)?$/);
	}
}

close(DNSTWIST) || die "dnstwist returned with non-zero exit code\n";

# print summary and full output for further debugging
my $num_problematic_lines = scalar @problematic_lines;

if ($num_problematic_lines == 0) {
	print("Found no problems in the following output:\n\n");
}
else {
	print("Found problems in the following lines:\n\n");
	print("------------------------------------------------------------\n");
	print(@problematic_lines);
	print("------------------------------------------------------------\n");
	print("\nDumping full output for further debugging purposes:\n\n");
}

print("------------------------------------------------------------\n");
print($log);

exit($num_problematic_lines);
