#!/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 $acct_info           = {};
my $time                = time();
my $cgroup_default_conf = '/opt/eig_linux/etc/default.conf';
my $cgroup_include_path = '/opt/eig_linux/etc/conf.d';
$acct_info->{hostname_prefix} = hostname() =~ s/\./_/rg;

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

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

if ( -f "$cgroup_default_conf" ) {
    open( FH, '<', $cgroup_default_conf ) or die $!;
    while (<FH>) {
        if (/^cpu_percent=(\d+)/) {
            $acct_info->{cpu_default_weight} = $1 / 100;
        }
    }
}

my @acct_data_raw = @{ decode_json(qx{/sbin/whmapi1 listaccts --output=json})->{data}->{acct} };

foreach my $acct_line (@acct_data_raw) {
    if ( $acct_line->{suspended} ) {
        $acct_info->{graphite_data}->{$time}->{'account-info'}->{suspended}++;
    }
    else {
        $acct_info->{graphite_data}->{$time}->{'account-info'}->{active}++;
        my $cpu_weight = cgroup_check( $acct_line->{uid} );
        $acct_info->{graphite_data}->{$time}->{'account-info'}->{active_weighted} += $cpu_weight ? $cpu_weight : $acct_info->{cpu_default_weight};
    }
}

sub cgroup_check {
    my $uid = shift;
    if ( -f "$cgroup_include_path/$uid.conf" ) {
        open( FH, '<', "$cgroup_include_path/$uid.conf" ) or die $!;
        while (<FH>) {
            if (/^cpu_percent=(\d+)/) {
                return $1 / 100;
            }
        }
    }
    return 0;
}

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