#!/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 $cpu_info = {};
my $time        = time();
$cpu_info->{hostname_prefix} = hostname() =~ s/\./_/rg;

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

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

chomp( my $cpu_data_raw = qx{/usr/bin/nproc} );

$cpu_info->{graphite_data}->{$time}->{'cpu'}->{nproc} = $cpu_data_raw;

my $graphite = Net::Graphite->new(
    host                 => $cpu_info->{statscollectserver}->{Host},
    port                 => $cpu_info->{statscollectserver}->{Port},
    trace                => 0,                                                # if true, copy what's sent to STDERR
    proto                => $cpu_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 => $cpu_info->{base_prefix}, data => $cpu_info->{graphite_data} );
