#!/usr/bin/perl
use warnings;
use strict;
use Getopt::Long;
use IO::Select;
use Term::ANSIColor qw(colored);
use XML::LibXML;

my %ignore = (
	'blocked' => 3,
	'disabled' => 1,
	'excluded' => 1,
	'succeeded' => 2,
);

my %norbl = (
	'blocked' => 1,
	'scheduled' => 1,
	'unresolvable' => 1,
);

my %colors = (
	'succeeded' => 'green',
	'blocked' => 'grey10',
	'broken' => 'red',
	'building' => 'grey15',
	'failed' => 'red',
	'scheduled' => 'grey10',
	'unresolvable' => 'red',
);

my $skip = 1;
my $cmd;
my $watch = 0;
GetOptions(
	"command=s" => \$cmd,
	"skip+" => \$skip,
	"watch:60" => \$watch,
) or die("Error in command line arguments\n");

my $in = \*STDIN if (!$cmd);
my $sel = IO::Select->new(\*STDIN) if ($watch);

{ do {
	if ($cmd) {
		open($in, "$cmd|") or die "cannot run '$cmd'";
	}

	my $dom = XML::LibXML->load_xml(IO => $in);

	my $max_len = 0;
	my %out;
	foreach my $res ($dom->findnodes('/resultlist/result')) {
		my $arch = $res->getAttribute('arch');
		my $project = $res->getAttribute('project');
		my $repo = $res->getAttribute('repository');

		foreach my $stat ($res->findnodes('./status')) {
			my $code = $stat->getAttribute('code');
			next if (defined $ignore{$code} && $ignore{$code} <= $skip);

			my $pkg = $stat->getAttribute('package');
			my $entry = "$pkg $code";
			my $entry_len = length $entry;
			$max_len = $entry_len if ($entry_len > $max_len);
			$entry = colored($entry, $colors{$code}) if ($colors{$code});
			my $rhs = $stat->findvalue('./details');
			my $rhs_empty = $rhs eq '';
			$rhs = colored($rhs, 'bright_yellow') unless $rhs_empty;
			if (!$norbl{$code}) {
				$rhs .= " (" unless $rhs_empty;
				$rhs .= "rbl $project $pkg $repo $arch";
				$rhs .= ")" unless $rhs_empty;
			}
			push @{$out{"$repo $arch"}}, [ $entry, $entry_len, $rhs ];
		}
	}

	close($in) if ($cmd);

	system('clear') if ($watch && scalar keys %out);

	foreach my $k (sort {
			my @a = split(/ /, $a);
			my @b = split(/ /, $b);
			$a[1] cmp $b[1] || $a[0] cmp $b[0];
		} keys %out) {
		print "$k\n";
		foreach my $o (@{$out{$k}}) {
			my ($entry, $entry_len, $rhs) = @{$o};
			my $spaces = $max_len - $entry_len + 3;
			print "   $entry", ' ' x $spaces, "$rhs\n";
		}
	}
	last unless (scalar keys %out);
	for (my $s = $watch; $s > 0; $s--) {
		printf "%s%3s", "\b" x 3, $s;
		select()->flush();
		sleep(1);
		while ($sel->can_read(0)) {
			exit(0) if (<STDIN> =~ /q/);
			$s = 0;
		}
	}
} while ($watch); }

1;
