#!/usr/bin/perl
#
# net_hsi_outbound_errors
#   Health check program for the Linux Health Checker
#
# Copyright IBM Corp. 2012
#
# Author(s): Nageswara R Sastry <nasastry@in.ibm.com>
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors: See file CONTRIBUTORS which is part of this package
#
#

use strict;
use warnings;

use lib $ENV{"LNXHC_LIBDIR"};
use LNXHC::Check::Base;


#
# Global variables
#

# Exception IDs
my $LNXHC_EXCEPTION_SLOW_HSI_RECEIVERS = "slow_hsi_receivers";

# Value of parameter 'txerror_ratio'.
my $param_txerror_ratio = $ENV{"LNXHC_PARAM_txerror_ratio"};

# Path to the file containing data for sysinfo item 'ifconfig'.
my $sysinfo_ifconfig = $ENV{"LNXHC_SYSINFO_ifconfig"};


#
# Code entry
#

check_int_param("txerror_ratio", 0, 100);

local *SI_FILE;
my @interface_data;
my $array_count = -1;
my %device_txerror;

open(SI_FILE, "<", $sysinfo_ifconfig) or
        die("net_hsi_outbound_errors: Could not read file '$sysinfo_ifconfig': ".
            "$!\n");
# Cretaing an array with only contents of the each interface
while (<SI_FILE>) {
	$array_count++ if (/^\S/);
	chomp;
	$interface_data[$array_count] .= $_;
}
close(SI_FILE);

# Checking for hsi interfaces
my $hsi_count = grep /^hsi/, @interface_data;
lnxhc_fail_dep("There are no hsi interfaces") unless $hsi_count;

# Collecting the hsi interface related data
foreach (@interface_data) {
	if (/^(hsi\d+).*TX packets:(\d+) errors:(\d+).*/) {
		my ($hsi_interface, $tx_packets, $current_txerrors) = ($1, $2, $3);
		my $tx_er_ratio = ($current_txerrors / $tx_packets) * 100
					if ($tx_packets != 0);
		if ($tx_er_ratio > $param_txerror_ratio) {
			# Collecting the data which is required for exception
			$device_txerror{$hsi_interface} = $current_txerrors;
		}
	}
}

# If hash contains some data then exception need to be raised
if (%device_txerror) {
	my @summary_device = sort(keys(%device_txerror));
	lnxhc_exception($LNXHC_EXCEPTION_SLOW_HSI_RECEIVERS);

	# Slicing the array to display in summary
	if (scalar(@summary_device > 4)) {
		@summary_device = (@summary_device[0..3], "...");
	}
	lnxhc_exception_var("summ_interface", join(", ", @summary_device));

	# Displaying all the interfaces and TX Errors
	lnxhc_exception_var("devices_txerrors",
		sprintf("#%-10s     %-20s", "Interface", "TX errors"));

	foreach my $device (sort keys(%device_txerror)) {
		lnxhc_exception_var("devices_txerrors",
			sprintf("#%-10s     %-20s", $device, $device_txerror{$device}));
	}
}

exit(0);
