#!/usr/bin/perl
# Dieses vom Kunden gelieferte Script wurde von Jeremy auf Wunsch von Team Admin
# überarbeitet, damit wir uns den Shell-Wrapper sparen können.
# Das Hauptdesignkriterium war, den Code des Kunden möglichst minimal zu
# modifizieren.


use strict;

use Getopt::Std;
use LWP::Simple qw(get);

my %opts;
my $session = 0;
my $count = 0;
my $sum = 0;
my $max = 0;
my $maxcomp = "";


getopts ("hH:w:c:m:", \%opts);
my $warning = $opts{w};
my $critical = $opts{c};
my $mode = $opts{m};
if ($opts{h}) {
	print "Usage $0 -H <HOST> -m <MODE> -w <WARN> -c <CRIT>\n";
	exit 0;
}

die "A -H(ost) must be given!\n" unless defined $opts{H};

die "A -m(ode) is needed!\n" unless defined $opts{m};

die "A -w(arning) threshold is needed!\n" unless defined $opts{w};

die "A -c(ritacl) threshold is needed!\n" unless defined $opts{c};

my $URL = "http://$opts{H}/is-bin/INTERSHOP.wastatistics";
my $DATA = get($URL);
unless($DATA) {
	print "Network Problems?\n";
	exit 1;
}
#print "$DATA\n";
#my $zeroInput = 1; # needed for: curl -m ... | wastats.pl   -> empty input on network errors should not make Notifications
my @lines = split(/\n/, $DATA);
#while ($DATA) {
foreach my $line (@lines) {
  my $zeroInput = 0;

  if ($line =~ m/^session:/) {
    $session = 1;
  }
  if ($line =~ m/^single:/) {
    $session = 0;
  }
  if ($session == 1) {
    if ($line =~ m/(\d+)\s+(\d.*?)\s+.*?\s+.*?\s+.*?\s+.*?\s+.*?\s+.*?\s+(.*?)\s/) { 
      #print "$1: $2: $3\n";
      $count++;
      $sum += $3;
      if ($3 > $max) {
	$max = $3;
	$maxcomp = $2;
      }
    }
  }
}

#if ($zeroInput == 1) {
#  print "Network problems?\n"; exit 1;
#}


if ($mode eq "count") {
  if ($count <= $critical) {
    print "Count = $count <= $critical\n";
    exit 2;
  } elsif ($count <= $warning) {
    print "Count = $count <= $warning\n";
    exit 1;
  } else {
    print "Count = $count\n";
    exit 0;
  }
} elsif ($mode eq "avg") {
  my $avg = $sum / $count;
  if ($avg > $critical) {
    print "Average = $avg > $critical (Max: $maxcomp $max)\n";
    exit 2;
  } elsif ($avg > $warning) {
    print "Average = $avg > $warning (Max: $maxcomp $max)\n";
    exit 1;
  } else {
    print "Average = $avg (Max: $maxcomp $max)\n";
    exit 0;
  }
} elsif ($mode eq "max") {
  my $avg = $sum / $count;
  if ($max > $critical) {
    print "Max = $maxcomp $max> $critical (Avg: $avg)\n";
    exit 2;
  } elsif ($max > $warning) {
    print "Max = $maxcomp $max> $warning (Avg: $avg)\n";
    exit 1;
  } else {
    print "Max = $maxcomp $max (Avg: $avg)\n";
  }
}
