#!/usr/bin/perl -w

use strict;
use warnings;
use LWP::Simple;
use Getopt::Long;
use JSON;

my $uri  = 'http://127.0.0.1/server-status';
my $what = 'all';
my $help = 0;

GetOptions(
  "uri=s"  => \$uri,
  "what=s" => \$what,
  "help"   => \$help
);

my %res = ();
my $status = get($uri . '?auto');


unless ($status){
  print 'ZBX_NOTSUPPORTED';
  exit 1;
}

foreach my $line (split(/\n/, $status)){
  next unless ($line =~ m/^(\w+(\s\w+)?):\s([\.\d]+)/);
  my ($key, $val) = ($1,$3);
  $key =~ s/\s/_/g;
  $key = lc $key;
  # Remove leading and trailing spaces
  $val =~ s/^\s+|\s+$//g;
  # Add 0 before the . when needed
  $val =~ s/^(\.\d+)$/0$1/;
  $res{$key} = $val;
}

if ($help){
  print "Valid keys are:\n\n";
  print "$_\n" for keys %res;
  exit 0;
}

if ($what eq 'all'){
  print to_json(\%res);
}
elsif (defined $res{$what}){
  print $res{$what};
}
else{
  print 'ZBX_NOTSUPPORTED';
}
exit 0;
