use warnings;

#Nagios Return Codes
$ng_ok = 0;
$ng_warn = 1;
$ng_crit = 2;
$ng_err = 3;

#Input
unless ($#ARGV == 2){
   print "Input must be: 'warnnum critnum allowedaccounts'\n";
   exit $ng_err;
}

($warn, $crit, $allowed) = @ARGV;

@sessions = ();
$plural = '';
@sessioninfo = `query session`;

foreach(@sessioninfo){
   chomp;
   s/^>/ /;
   next unless /active/i;
   @list = split(/\s+/);
   push @sessions, $list[2];
}

foreach(@sessions){
   if ($allowed !~ /\Q$_\E/i){
      print "Critical: $_ login is not in allowed users list.\n";
      printsessions(@sessions);
      exit $ng_crit;
   }
}

$sessions = $#sessions + 1;
$plural = 's' if ($sessions > 1 || $sessions == 0);

if ($sessions >= $warn && $sessions < $crit){
   print "Warning: $sessions user$plural logged in\n";
   printsessions(@sessions);
   exit $ng_warn;
   }

if ($sessions >= $crit){
   print "Critical: $sessions user$plural logged in\n";
   printsessions(@sessions);
   exit $ng_crit;
}

print "OK: $sessions user$plural logged in\n";
printsessions(@sessions);
exit $ng_ok;

print "Unknown: Some unhandled error occurred\n";
exit $ng_err;

sub printsessions{
   my @list = @_;
   print "Active Sessions:";
   foreach (@list){
      print " $_";
   }
   print "\n";
}
