#!/usr/bin/env perl
#
# Copyright IBM Corp. 2017,2020
#
# Usage: check_counts <counts_file> <output_file>
#
# Compare the lcov/genhtml summary output in <output_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, $output) = @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;

if (!defined($counts) || !defined($output)) {
    die("Usage: $0 <counts_file> <coverage_data_file>\n");
}

open($fd, "<", $output) or die("$0: Could not read $output: $!\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 output for $output 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);
