#!/usr/bin/perl
use warnings;
use strict;

use IO::Socket::INET;
use Data::Dump qw(dump);

my $sock = IO::Socket::INET->new(
	PeerAddr => '127.0.0.1',
	PeerPort => 4730,
	Proto    => 'tcp'
) || die $1;

print "[2J"; # Erase Screen

my $t = time();
my $max;

while(1) {
	my $uptime = time() - $t;
	print "[2J" if $uptime % 30 == 0;
	print "[0;0H"; # Cursor Home
	print "Gearman " . localtime(time()) . "\t[34mmax update: $uptime[0m\n"; 
	printf "[4mqueued  running  wrk function[0m\n";

	print $sock "STATUS\n";

	while ( my $line = <$sock> ) {
		chomp $line;
#		warn "# [$line]\n";
		last if $line eq '.';
		next if $line =~ m/\t0$/; # ignore functions which don't have active workers
		my ( $name, $queued, $running, $workers ) = split(/\t/,$line,4);
		$max->{$name}->{$_} ||= 0 foreach qw(queued running);
		$max->{$name}->{queued}  = $queued  if $queued > $max->{$name}->{queued};
		$max->{$name}->{running} = $running if $running > $max->{$name}->{running};
		printf "%3d [34m%-3d[0m %3d [34m%-3d[0m %3d  %s\n"
			, $queued,  $max->{$name}->{queued}
			, $running, $max->{$name}->{running}
			, $workers
			, $name
		;
	}

=for workers
	print $sock "WORKERS\n";

	while ( my $line = <$sock> ) {
		chomp $line;
		warn "# [$line]\n";
		last if $line eq '.';
	}
=cut

	sleep 1;
}
