#!/usr/bin/perl

use strict;
use warnings;
use JSON::XS;
use Config::General qw(ParseConfig);
use IO::Socket::INET;
use Net::Graphite;
use Sys::Hostname;
use Data::Dumper;

my $apache_info = {};
my $time        = time();
$apache_info->{hostname_prefix} = hostname() =~ s/\./_/rg;

my %config = ParseConfig( -ConfigFile => "/etc/collectd.conf", -AutoTrue => 1 );

$apache_info->{statscollectserver} = $config{Plugin}->{write_graphite}->{Node}->{statscollectserver};
$apache_info->{base_prefix}        = "$apache_info->{statscollectserver}->{Prefix}$apache_info->{hostname_prefix}";

chomp( my @apache_data_raw = qx{timeout -s 9 15 lynx --dump --width=10000 localhost/whm-server-status?auto | grep -P '^(Processes|Stopping):'} );

foreach my $apache_line (@apache_data_raw) {
    my ( $key, $value ) = split( " ", $apache_line );
    if ( $key eq "Processes:" ) {
        $apache_info->{graphite_data}->{$time}->{'apache-apache'}->{apache_processes} = $value;
    }
    elsif ( $key eq "Stopping:" ) {
        $apache_info->{graphite_data}->{$time}->{'apache-apache'}->{apache_processes_stopping} = $value;
    }
}

my $graphite = Net::Graphite->new(
    host                 => $apache_info->{statscollectserver}->{Host},
    port                 => $apache_info->{statscollectserver}->{Port},
    trace                => 0,                                                # if true, copy what's sent to STDERR
    proto                => $apache_info->{statscollectserver}->{Protocol},
    timeout              => 5,                                                # timeout of socket connect in seconds
    fire_and_forget      => 0,                                                # if true, ignore sending errors
    return_connect_error => 1,                                                # if true, forward connect error to caller
    flush_limit          => 0,                                                # if true, send after this many metrics are ready
);

$graphite->send( path => $apache_info->{base_prefix}, data => $apache_info->{graphite_data} );
