#!/usr/local/bin/perl

# These are the variables passed to each function call.
#
# $_[0] = name for this module (surely you already know this, but still)
# $_[1] = sending nickname
# $_[2] = sending username
# $_[3] = sending hostmask
# $_[4] = sending channel (or botnick in case of PM)
# $_[5] = current value for $modchan
# $_[6] = current value for $botnick
# $_[7] = first argument given in IRC
# $_[8] = second argument given in IRC etc.

package toolbox;

sub public {
	@public = ("help", "dig", "whois", "ping");
}


# sub help {} is a special name, if you implement this subroutine it will be called when your module is called with no parameters.
# Implementing the mesg subroutine is optional, but highly reckomended.
sub help {
	nanobot::snd("NOTICE $_[1] :Commands: help, dig, ping");
}

sub dig {
	if ($_[7] =~ /^([[:alnum:]]+[.-]{0,1})+\.[[:alpha:]]{1,4}$/) {
		open(DIG, "dig +short $_[7] |");
			my @result = <DIG>;
		close(DIG);
		nanobot::msg("$_[4]", "Hostname: $_[7] -> @result");		
	} elsif ($_[7] =~ /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/) {
		open(DIG, "dig +short -x $_[7] |");
			my @result = <DIG>;
		close(DIG);
		nanobot::msg("$_[4]", "IPv4: $_[7] -> @result");
	} else {
		nanobot::msg("$_[4]", "Not a valid hostname.");
	}
}

sub ping {
	if ($_[7] =~ /^([[:alnum:]]+[.-]{0,1})+\.[[:alpha:]]{1,4}$/) {
		open(PING, "ping -c1 $_[7] |");
			my @result = <PING>;
		close(PING);
		nanobot::msg("$_[4]", "Hostname: $_[7] -> $result[1]");
	} elsif ($_[7] =~ /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/) {
		open(PING, "ping -c1 $_[7] |");
			my @result = <PING>;
		close(PING);
		nanobot::msg("$_[4]", "IPv4: $_[7] -> $result[1]");		
	} elsif ($_[7] =~ /^\s*((([0-9A-Fa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
			my @result = <PING>;
		close(PING);
		nanobot::msg("$_[4]", "IPv6: $_[7] -> $result[1]");
	} else {
		nanobot::msg("$_[4]", "Not a valid hostname or IP address.");
	}	
}

# A module must always end with the line "1;", Perl demands it.
1;
