#!/usr/bin/perl -w
#
# NAGIOS Plugin: check_bsnl
# Check the status of the internet usage using the output of the bsnl.sh script
# Author: John Jore <j o h n a t j o r e d ot n o>
# Version 0.1
# This is not pretty as its my first Perl script. Anyone care to maul over it and clean it up?

use strict;
use File::Basename;
use vars qw(
	$progname
	$state_ok
	$state_warning
	$max_per_month
	$days_per_month
	$current_day
	$command
	$bsnl_used
	$state_out
	$desc_out
	$exit_out
	$stat
        $threshold_ok
        $threshold_warning
	$max_today
	$stat_procent
	);

$progname = basename($0);

#Constants to set, depending on your environment
$max_per_month=50; #Monthly allowance
$days_per_month=30; #Days per month
$state_ok=20; #in procent
$state_warning=10; #in procent
$bsnl_used = "/tmp/bsnl_nagios"; 


# - Nothing to change below this line -

#How much is used as of today? Read from the file
open (BSNL, $bsnl_used);
$stat = <BSNL>;
chomp($stat);
$stat = sprintf "%.1f",$stat;
#print "Current usage: $stat\n";

#Get current day of month
$command = "date +%d";
$current_day = qx ( $command );
#print "Current day: $current_day\n";

#Max we should have used by today
$max_today = $max_per_month / $days_per_month * $current_day;
#Round number off to 2 decimals
$max_today = sprintf "%.1f",$max_today;
#print "Max for today: $max_today\n";

#These are the two thresholds. Usage is above or below these numbers determine the status (OK, Warning, Critical)
$threshold_ok = $max_today - ($max_today * $state_ok) / 100;
$threshold_warning = $max_today - ($max_today * $state_warning) / 100;
$threshold_ok = sprintf "%.1f",$threshold_ok;
$threshold_warning = sprintf "%.1f",$threshold_warning;
#print "Ok: $threshold_ok   Warning: $threshold_warning\n";

#How much of our allowance is used, in %
$stat_procent = $stat*100/$max_today;
$stat_procent = sprintf "%.1f",$stat_procent;

if ($threshold_ok and $threshold_warning) {
  if ($stat <= $threshold_ok) {
    $state_out = "OK";
    $desc_out = "Usage is $stat GB of $max_today GB, ($stat_procent%)";
    $exit_out = 0;
  }

  if (!$state_out) {
    if ($stat <= $threshold_warning) {
      $state_out = "WARNING";
      $desc_out = "Usage is $stat GB of $max_today GB, ($stat_procent%)";
      $exit_out = 1;
    }
  }

  if (!$state_out) {
    $state_out = "CRITICAL";
    $desc_out = "Usage is $stat GB of $max_today GB, ($stat_procent%)";
    $exit_out = 2;
  }
}

if (!$state_out) {
  $state_out = "UNKNOWN";
  $desc_out = "Usage is $stat GB of $max_today GB, ($stat_procent%)";
  $exit_out = 3;
}

print "$progname: $state_out ($desc_out)\n";
exit $exit_out;
