#!/usr/bin/perl
#
# $Revision: 1.10 $
# General network tests and logging.
#

use strict;
use warnings;
use Net::Ping;
use LWP::Simple;
use Time::HiRes qw(tv_interval gettimeofday);
use POSIX;
use Getopt::Long;
use File::Basename;
use Sys::Hostname;

my $progname = basename($0);
my $host;
my $count = 0;
my $speed = "";
my $help = 0;
my $version = 0;
my $wanip = 0;
my @host_array = ();
my $logmsg = "";
my $teleflora = "tws.teleflora.com";
my $nmap = "";
my $portlist = "80";
my $sleep = 60;
my $stats = 0;
my $rx = "";
my $tx = "";
my $interface = "eth0";
my $email = "";
my $recipient = "";
my $message = "";
my $path = "/tmp/";
my $today = strftime("%d", localtime());
my $tomorrow = strftime("%d", localtime());
my $file = "Network_Test-Day_$today.log";
my $hostname = hostname; 
my $subject = "Nettest Scan Results from $hostname";

# Add new addresses to scan.	

push (@host_array,"192.168.1.1");
push (@host_array,"192.168.1.51");
push (@host_array,"192.168.1.21");
push (@host_array,"www.yahoo.com");
push (@host_array,"igusproda.globalpay.com");
push (@host_array,"igusprodb.globalpay.com");

GetOptions(
	"help" => \$help,
	"version" => \$version,
	"count=s" => \$count,
	"wanip" => \$wanip,
	"stats" => \$stats,
	"email=s" => \$email,
	"speed" => \$speed,
);

if($help != 0) {
	usage();
	exit(0);
}

if($version != 0) {
	print("\n");
	print("$progname\n");
	print("\n");
	exit(0);
}

if($count != 0) {
	scan($count);
	exit(0);
}

if($wanip !=0) {
	wanip();
	print("$wanip $hostname\n");
	exit(0);
}

if($stats != 0) {
	stats();
	exit(0);
}

if("$email" ne "") {
	if(-e "$path$file") { 
		loginfo("\n");
		loginfo("     -- Emailed results to $email\n");
		email();
		exit(0);
	} else {
		print("Error No File to Email\n");
		exit(0);
	}
}

if("$speed" != 0) {
	speed();
	exit(0);
}

usage();
exit(0);

###################################################################

sub ping
{
	my $timeelapsed = "";
	my $timestart = "";
	my $ping = "";

	$ping = Net::Ping->new('icmp');
	foreach $host (@host_array) {
    		$timestart = [gettimeofday()];
  		if ($ping->ping($host, 2)) {
       		$timeelapsed = tv_interval($timestart, [gettimeofday()]);
		loginfo(sprintf("up   -- %s: %.3f msec\n", $host, $timeelapsed * 1000));
    		} else {
       		$timeelapsed = tv_interval($timestart, [gettimeofday()]);
       		loginfo(sprintf("down -- %s: %.3f\n", $host, $timeelapsed * 1000));
    		}
	}
	$ping->close();
}

sub nmap
{
	open(PIPE, "/usr/bin/nmap -P0 $teleflora -p80|grep open |");
	while(<PIPE>){
		chomp;
		$nmap = $_ ;
	}
	close(PIPE);
	if($nmap =~ /(80\/tcp)(\s+)(open)(\s+)(http)/){
		#$logmsg = "Nmap : \n";
		#$logmsg .= " \"$nmap\"\n";
		loginfo("open -- $teleflora $nmap\n");
	} else {
		$logmsg = "Nmap : \n";
		loginfo("nmap -- $teleflora $nmap\n");
	}
}

sub scan 
{
	loginfo("     -- Test Started\n");
	wanip();
	loginfo("info -- Test will run for $count minutes\n");
	while ($count >= 1 ) {
		loginfo("\n");
		ping();
		nmap();
		$count --;
		sleep $sleep;
	}

	loginfo("\n");
	loginfo("     -- Test Complete\n");
	if("$email" ne "") {	
		if(-e "$path$file") {
		loginfo("\n");
		loginfo("     -- Emailed results to $email\n");
		email();
	} 
	exit(0);	
}
}

sub email
{
        open(MUTT, "| mutt -s \"$subject\" $email < $path$file");
        print(MUTT $message);
        close(MUTT);
}

sub stats 
{
	my $loop = 1;
	my @RX = ();
	my @TX = ();
	my $rec = "";
	my $send = "";
	my $delay = 5;
	
	while ($loop <=2) {
	open(ETH, "/sbin/ethtool -S $interface |");
	while(<ETH>) {
		chomp;
		if(/(rx_bytes:)(\s+)/) {
			$rx =$_; 
			$rx =~ s/^\s+//;
			$rx =~ s/rx_bytes: //;
			$RX[$loop] = int($rx);
		}
		if(/(tx_bytes:)(\s+)/) {
			$tx =$_;
			$tx =~ s/^\s+//;
			$tx =~ s/tx_bytes: //;
			$TX[$loop] = int($tx);
		}
	}
	close(ETH);
	sleep 1;
	$loop ++;
	}
	$rec = int($RX[2]) - int($RX[1]);
	$send = int($TX[2]) - int($TX[1]);
	loginfo("--   -- Traffic on interface $interface\n");
	loginfo("Tx   -- Tx Bytes/sec = $send\n");
	loginfo("Rx   -- Rx Bytes/sec = $rec\n");
}

sub usage
{
	print(<< "EOF");

$progname Usage:
$progname --version   -- Print version.
$progname --help      -- This output.
$progname --count     -- Number of loops to do.
$progname --wanip     -- Print/Log Wan IP address.
$progname --stats     -- Print/Log tx/rx bytes on ethx.
$progname --email     -- Email test results.
		               You can receive an email of the test results
			       by adding the option --email=me\@somewhere.com.
			       Existing results can also be emailed without 
			       preforming a test first.
$progname --speed     -- Test download speed.

Example: $progname --count=2 --email=me\@somewhere.com
	 This will scan for 2 minutes and send an email when complete.

Example: $progname --email=me\@somewhere.com
	 This example will email an existing log.

Example: $progname --stats
	 This example will measure in bytes the traffic on $interface.

EOF
}

sub wanip
{
	open(PIPE, "curl -s http://www.ipchicken.com/ |");
	while(<PIPE>){
		chomp;
		if($_ =~ /([\d]+)\.([\d]+)\.([\d]+)\.([\d]+)/){
			$wanip = $_ ;
			$wanip =~ s/^\s+//;
			$wanip =~ s/\s+//;
			$wanip =~ y/[<br>]//d;
			$wanip =~ s/\r//g
		}
	}
	close(PIPE);
	loginfo("ip   -- $wanip $hostname\n");
}

sub loginfo
{
	my $timestamp = strftime("%Y-%m-%d %H:%M:%S", localtime());
	open(LOGFILE, ">> /tmp/Network_Test-Day_$today.log");
	print(LOGFILE "$timestamp -- @_");
	close(LOGFILE);
}

sub speed
{
	my $start = gettimeofday();
	get("http://rtihardware.homelinux.com/ostools/testfile.txt");
	my $end = gettimeofday();
	my $delta = ($end - $start);
	my $time = (1 / $delta);
	$time = sprintf("%.3f", $time);
	loginfo("ip   -- Download speed = $time Megs/sec\n");
}

