#!/usr/bin/env perl
#
# Copyright IBM Corp. 2017
#
# Usage: check_counts <counts_file> <coverage_data_file>
#
# Compare the output of "lcov --summary" for <coverage_data_file> with the
# coverage data counts specified in <counts_file>. This file has the following
# format (all in a single line):
#
#   lnhit lnfound fnhit fnfound brhit brfound2
#

use strict;
use warnings;

sub do_cmp($$$)
{
	my ($title, $a, $b) = @_;

	if ($a == $b) {
		print("$title: $a == $b\n");
		return 0;
	} else {
		print("$title: $a != $b => mismatch!\n");
		return 1;
	}
}

my $lcov = $ENV{"LCOV"};
my ($counts, $info) = @ARGV;
my $fd;
my $cmdline;
my ($lnhit, $lnfound, $fnhit, $fnfound, $brhit, $brfound) = (0, 0, 0, 0, 0, 0);
my ($lnhit2, $lnfound2, $fnhit2, $fnfound2, $brhit2, $brfound2);
my $rc = 0;

die("$0: LCOV environment variable not defined\n") if (!defined($lcov));
if (!defined($counts) || !defined($info)) {
	die("Usage: $0 <counts_file> <coverage_data_file>\n");
}

$cmdline = "$lcov --summary $info";
open($fd, "-|", $cmdline) or die("$0: Could not run $cmdline: $!\n");
while (<$fd>) {
	($lnhit, $lnfound) = ($1, $2) if (/(\d+) of (\d+) lines/);
	($fnhit, $fnfound) = ($1, $2) if (/(\d+) of (\d+) functions/);
	($brhit, $brfound) = ($1, $2) if (/(\d+) of (\d+) branches/);
}
close($fd);

die("$0: Non-zero result code ($?) of command: $cmdline\n") if ($? != 0);

open($fd, "<", $counts) or die("$0: Could not open $counts: $!\n");
if (<$fd> !~ /^(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/) {
	die("$0: Invalid count file: $counts\n");
}
($lnhit2, $lnfound2, $fnhit2, $fnfound2, $brhit2, $brfound2) =
	($1, $2, $3, $4, $5, $6);
close($fd);

print("Comparing --summary output for $info and $counts:\n");
$rc |= do_cmp("line hit", $lnhit, $lnhit2);
$rc |= do_cmp("line found", $lnfound, $lnfound2);
$rc |= do_cmp("functions hit", $fnhit, $fnhit2);
$rc |= do_cmp("functions found", $fnfound, $fnfound2);
$rc |= do_cmp("branches hit", $brhit, $brhit2);
$rc |= do_cmp("branches found", $brfound, $brfound2);

exit($rc);
