#!/usr/bin/perl
#%# family=auto
#%# capabilities=autoconf

use strict;

use LWP;
use JSON;

###
# Infos about HTTP keepalive:
#   hits count:    Requests that get handled via a "keep-alive" enabled connection.
#   live count:    The number of live keep-alive connections.
#   refuses count: the number of times keep-alive mode was refused.
#   timeouts cout: Connections that weren't closed to signal completion according to HTTP1.0/1.1 but simply timed out. 
###

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

my $url = $ENV{oxJolokiaUrl};
my $username = $ENV{oxJolokiaUser};
my $password = $ENV{oxJolokiaPassword};
if ( $ARGV[0] and $ARGV[0] eq "config") {
    print "graph_title AsyncAppender Queue Sizes\n";
    print "graph_category Open Xchange\n";
    print "graph_vlabel total\n";

    my $output = callUrl("stats","/read/com.openexchange.logging:name=Logging Configuration/RootAppenderStats");
    my @lines = split('\n', $output);
    my $i = 0;
    foreach my $line (@lines) {
        if ($line =~ /AsyncAppender:\s([^\[]+)\s\[capacity=([\d]+),size=([\d]+)/) {
            print "a$i.label $1 (capacity: $2)\n";
            my $w = int($2 / 2);
            print "a$i.warning :$w\n";
            print "a$i.critical :$2\n";
            $i++;
        } elsif ($line =~ /LogstashSocketAppender:\s([^\[]+)\s\[capacity=([\d]+),size=([\d]+)/) {
            print "a$i.label $1 (capacity: $2)\n";
            my $w = int($2 / 2);
            print "a$i.warning :$w\n";
            print "a$i.critical :$2\n";
            $i++;
        }
    }
    exit 0
}

my $output = callUrl("stats","/read/com.openexchange.logging:name=Logging Configuration/RootAppenderStats");
my @lines = split('\n', $output);
my $i = 0;
foreach my $line (@lines) {
    if ($line =~ /AsyncAppender:\s([^\[]+)\s\[capacity=([\d]+),size=([\d]+)/) {
        print "a$i.value $3\n";
        $i++;
    } elsif ($line =~ /LogstashSocketAppender:\s([^\[]+)\s\[capacity=([\d]+),size=([\d]+)/) {
        print "a$i.value $3\n";
        $i++;
    }
}

sub callUrl {
    my $ua = LWP::UserAgent->new();
    my $req = HTTP::Request->new(GET => "$url$_[1]");
    $req->authorization_basic($username,$password);

    $req->header('Accept', => 'text/html');

    my $response = $ua->request($req);

    if ($response->is_success) {
        my $json = decode_json($response->decoded_content);
        if (defined $json->{value}) {
            return $json->{value};
        }
    } else {
        my $status = $response->status_line;
        if ($status == 404) {
            die "Link to servlet might not be set correctly, this can be done by altering /etc/munin/plugin-conf.d/ox and setting the correct path to your jolokia servlet";
        } elsif ($status == 401) {
            die "Credentials to login might be not set correctly. The credentials are set inside /opt/open-xchange/etc/jolokia.properties on the OX, for munin, those need to be altered at /etc/munin/plugin-conf.d/ox";
        } else {
            die "Something went wrong:\n",$status;
        }
    }

    die "can not read monitoring output\n";
}