#!/usr/bin/perl

use strict;
use warnings;

my @HOSTS=("172.16.0.1","172.16.0.2","172.16.0.3","172.16.0.10","-",
           "172.16.0.21","172.16.0.31","-",
           "ya.ru");
my $PINGCNT=5;
my $SLEEPTIME=1;
my $INTERVAL=0.001;
my $ITER=4;

sub cprint($) {
      $_[0] //= 0;
      if ($_[0] == $PINGCNT) { printf "\e[1;32m%2d\e[0m",$_[0]; }
      elsif ($_[0] == 0)     { printf "\e[1;31m%2d\e[0m",$_[0]; }
      else                   { printf "\e[1;33m%2d\e[0m",$_[0]; }
}

my $cnt;
my @DT = ("")x$ITER;
my @PACKETCNT;
my @PACKETRTT;

while (1) {
   $_ = qx`date "+%H:%M:%S"`;			#qx to supress interpolation of hash-like %
   chomp;
   @DT[0..$ITER-1] = ($_,@DT[0..$ITER-2], $_);

   $cnt = 0;
   foreach my $HOST (@HOSTS) {
      if ($HOST ne "-") {
         $cnt++;
         @{$PACKETCNT[$cnt]}[1..$ITER-1] = @{$PACKETCNT[$cnt]}[0..$ITER-2];
         @{$PACKETRTT[$cnt]}[1..$ITER-1] = @{$PACKETRTT[$cnt]}[0..$ITER-2];
               
         ($PACKETCNT[$cnt][0],$PACKETRTT[$cnt][0]) = (
            `ping -c $PINGCNT -i $INTERVAL -q $HOST` =~ 
            /(\d+)\s+received.*rtt.*[=\s]+[\d\.]+\/([\d\.]+)\//s
            );
         }
      }

   system "clear";
   $cnt=0;
   
   print "----+----------------------"."+----------------"x$ITER."|\n";
   print "SEQ |       Address        ";
   printf "|    %8s    "x$ITER, @DT[0..$ITER-1];
   print "|\n";
   
   print "----+----------------------"."+----------------"x$ITER."|\n";
   foreach my $HOST (@HOSTS) {
      if ($HOST eq "-") {
         print "----+----------------------"."+----------------"x$ITER."|\n";
         }
      else {
         $cnt++;
         printf "%3d | %20s | ",$cnt,$HOST;
         for (my $i=0; $i<$ITER; $i++) {
            cprint($PACKETCNT[$cnt][$i]);
            printf " %8s ms | ",$PACKETRTT[$cnt][$i]//"";
            }
         print "\n";
         }
      }
   print "----+----------------------"."+----------------"x$ITER."+\n";
   sleep $SLEEPTIME;
   }
