#!/usr/bin/perl

use strict;
use warnings;

use FindBin;
use lib "$FindBin::Bin/../../lib";
use Wigo::Probe qw/:all/;

###
# DEFAULT CONFIG
###

my $conf = {
    'toCheck'           => 1,
    'warnPercentage'    => 150,
    'critPercentage'    => 200
};

init( config => $conf );

# Number of cores
my $cores = `grep -c '^processor' /proc/cpuinfo`;
chomp $cores;
$cores ||= 1;

if ( ! open LOADAVG, '<', '/proc/loadavg' )
{
    status  500;
    message "Error while fetching loadavg : " . $!;
    output 1;
}
my $loadavg = <LOADAVG>;
close LOADAVG;
chomp $loadavg;

if ( $loadavg =~ /^([\d\.]+)\s([\d\.]+)\s([\d\.]+)/ )
{
    my $rawValue1  = $1;
    my $rawValue5  = $2;
    my $rawValue15 = $3;

    message "$rawValue1 $rawValue5 $rawValue15";

    metrics [
        { Tags => { "load" => "load1" },  Value => $rawValue1 },
        { Tags => { "load" => "load5" },  Value => $rawValue5 },
        { Tags => { "load" => "load15" }, Value => $rawValue15 },
    ];

    my $toCheck;
    # == 10: keeping this due to previous in incorrect version of the probe
    # to avoid breaking preexisting configs
    if ( config->{'toCheck'} == 2 or config->{'toCheck'} == 10 or config->{'toCheck'} == 5 )
    {
        $toCheck = $rawValue5;
    }
    elsif ( config->{'toCheck'} == 3 or config->{'toCheck'} == 15 )
    {
        $toCheck = $rawValue15;
    }
    else
    {
        $toCheck = $rawValue1;
    }

    my $percentage = $toCheck * 100 / $cores;
    if ( $percentage > config->{'critPercentage'} )
    {
        raise 300;
    }
    elsif ( $percentage > config->{'warnPercentage'} )
    {
        raise 200;
    }
}
else
{
    status 500;
    message "Can't parse loadavg : " . $loadavg;
    output 1;
}

output 0;
