#!/usr/bin/perl
# -*- perl -*-

# Copyright (C) 2015 Pirx Developers - https://pirx.dev/
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

=head1 NAME

hq_loadavg - Munin plugin to monitor system load average.

=head1 APPLICABLE SYSTEMS

Linux systems.

=head1 CONFIGURATION

You may want to configure warning and critical thresholds
in your munin node configuration:

[hq_loadavg]
  env.warning 5
  env.critical 10

Default thresholds are 5 for warning and 10 for critical.

=head1 VERSION

  20151019

=head1 MAGIC MARKERS

  #%# family=manual
  #%# capabilities=autoconf

=head1 BUGS

None.

=head1 AUTHOR

Pirx Developers - https://pirx.dev/

=head1 LICENSE

GPLv3

=cut

use strict;
use warnings;

# Handle autoconf
if(defined($ARGV[0]) and $ARGV[0] eq 'autoconf') {
  print("yes\n");
  exit(0);
}

# Get current loadavg
my $loadavg = `cut -d' ' -f 2 /proc/loadavg 2>/dev/null`;
chomp($loadavg);

# set warning and critical thresholds
my $warning = 5;
my $critical = 10;
if(defined($ENV{'warning'})) {
  $warning = $ENV{'warning'};
}
if(defined($ENV{'critical'})) {
  $critical = $ENV{'critical'};
}

# Handle config
if(defined($ARGV[0]) and $ARGV[0] eq 'config') {
  # Choose color for graph depending on usage warning levels
  my $graph_color = "00d000";
  if($loadavg > $warning) {
    $graph_color = "ff8500";
  }
  if($loadavg > $critical) {
    $graph_color = "ff0000";
  } 
  print <<EOF;
graph_title System load average
graph_args --base 1000 --lower-limit 0
graph_scale no
graph_vlabel load
graph_category system

loadavg.label loadavg
loadavg.type GAUGE
loadavg.min 0
loadavg.draw AREA
loadavg.colour $graph_color
loadavg.line $warning:b0b0b0:Warning threshold
loadavg.warning $warning
loadavg.critical $critical
EOF
  exit(0);
}

printf("loadavg.value %.2f\n", $loadavg);

exit(0);
