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

use strict;

use LWP;
use JSON;

my $url = $ENV{oxJolokiaUrl};
my $username = $ENV{oxJolokiaUser};
my $password = $ENV{oxJolokiaPassword};


if ( $ARGV[0] and $ARGV[0] eq "autoconf")
{
	callUrlForConfig("/search/com.openexchange.solr:type=solrControl/ActiveCores");
	exit 0;
}

if ( $ARGV[0] and $ARGV[0] eq "config") {
    print "graph_title Solr Cores\n";
    print "graph_category Open Xchange\n";
    print "graph_vlabel total\n";
    print "a.label active solr cores\n";
    exit 0
}

callUrl("a","/read/com.openexchange.solr:type=solrControl/ActiveCores");

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}){
			my @array = @{$json->{value}};
			my $arraySize = @array;
			
			print "$_[0]".".value ";
			print "$arraySize\n";
		}
	}
	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;
		}

		print STDERR $response->status_line, "\n";
	}
}

sub callUrlForConfig {
	my $ua = LWP::UserAgent->new();
	my $req = HTTP::Request->new(GET => "$url"."$_[0]");
	$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}->[0]){
			print "yes\n";
		} else {
			print "no\n";
		}
	}
	else {
		print "no\n";
		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;
		}

		print STDERR $response->status_line, "\n";
	}
}