#!/usr/bin/perl
use warnings;
use strict;
$|=1;

my $opt_f = "/proc/stat";         # file to read from
my $opt_e = ""; # '(\S+) (\S+( \S+){0,15}).*'; # regex to apply
my $opt_h = ''; # regex to apply
my $opt_k = '(\S+)'; # regex to apply
my $opt_v = ' (\S+( \S+){0,15}).*'; # regex to apply
my $opt_N = 0; # do NOT whitespace-normalize

my $opt_w = 30;
my $opt_c = 35;

use Getopt::Long qw(:config no_ignore_case bundling);
GetOptions(
        'f=s' => \$opt_f,
        'e=s' => \$opt_e,
        'h=s' => \$opt_h,
        'k=s' => \$opt_k,
        'v=s' => \$opt_v,
        'N'   => \$opt_N,
        ) or die "funnyargs";

my @expr = ();
if (length $opt_e) {
	@expr = split "^", $opt_e;
} else {
	push @expr, "$opt_h$opt_k$opt_v";
}

my ($msg, $perf,);
my $ec = 3;

my $rc = eval { 
	my $fn = $opt_f;
	die "'$fn' does not exist" unless -e $fn;
	die "'$fn' not a file" unless -f $fn;
	open IF, "<", $fn or die "open($fn): $!";

	my @perf = ();
	my $c = 0;
	while (<IF>) {
		$c++;
		unless ($opt_N) {
			s/[\s\r\n]+/ /g;
			s/(^ | $)//g;
		}

		for my $e (@expr) {
			if (/^$e$/) {
				my ($k,$v,) = ($1,$2,);
				$v =~ s/ /;/g;
				push @perf, sprintf("%s=%s;",$k,$v);
			}
		}
	}
	close IF;

	$msg = sprintf "%i read, %i perf", $c, scalar @perf;
	$perf = join(" ",sort @perf);

	return "ok";
};

if (defined $rc && $rc eq 'ok') {
	$msg ||= sprintf "%i perfbytes", length $perf;
	$ec = 0;
} else {
	$ec = 3;
	if ($@) {
		chomp $@;
		$msg = "EXCEPTION: '$@'";
	} else {
		$msg = "UNKNOWNRC: '$rc'";
	}
}
unless (defined $msg && length $msg) {
	$msg = "NOMESSAGE";
	$ec = 3;
}

#TODO
$perf ||= "";

my $st = {
		0 => 'OK',
		1 => 'WARNING',
		2 => 'CRITICAL',
		3 => 'UNKNOWN',
	}->{$ec}||"EC$ec";

printf "%s - %s|%s\n", $st, $msg, $perf;

exit $ec;



