#!/usr/bin/perl
#
# check_entropy - Monitor systems entropy
# Copyright (C) 2016 Josef 'veloc1ty' Stautner (hello@veloc1ty.de)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

use strict;
use Getopt::Long;

our $ARG_WARNING_VALUE = 400;
our $ARG_CRITICAL_VALUE = 200;

sub isInt {
    my $possibleInt = shift;

    return 1 if ( $possibleInt =~ /\d+/ );
    return 0;
}

sub exitUnknown {
    printf("UNKNOWN - %s\n", shift);
    exit(3);
}

sub exitCritical {
    printf("CRITICAL - %s\n", shift);
    exit(2);
}

sub exitWarning {
    printf("WARNING - %s\n", shift);
    exit(1);
}

sub parseArguments {
    GetOptions (
        'warning=i' => \$ARG_WARNING_VALUE,
        'critical=i' => \$ARG_CRITICAL_VALUE
    );

    exitUnknown('--warning isn\'t a number') if ( ! isInt($ARG_WARNING_VALUE));
    exitUnknown('--critical isn\'t a number') if ( ! isInt($ARG_CRITICAL_VALUE));

    if ( $ARG_WARNING_VALUE < $ARG_CRITICAL_VALUE ) {
        exitUnknown('--warning has to be greater that --critical')
    }
}

sub getEntropy {
    my $possibleEntropy = `cat /proc/sys/kernel/random/entropy_avail`;
    chomp($possibleEntropy);

    if ( ! isInt($possibleEntropy) ) {
        exitCritical('Was not able to fetch available entropy');
    }

    return $possibleEntropy;
}

sub main {
    parseArguments();

    my $availableEntropy = getEntropy();
    my $availableEntropyString =
        sprintf('Available: %d|available_entropy=%d;%d;%d',
            $availableEntropy, $availableEntropy, $ARG_WARNING_VALUE,
            $ARG_CRITICAL_VALUE);


    if ( $availableEntropy < $ARG_CRITICAL_VALUE ) {
        exitCritical(sprintf('Not enogh entropy! %s', $availableEntropyString));
    }
    elsif ( $availableEntropy < $ARG_WARNING_VALUE ) {
        exitWarning(sprintf('Slightly few entropy! %s', $availableEntropyString));
    }
    else {
        printf("OK - Entropy is just fine! %s\n", $availableEntropyString);
    }
}

main();
