#!/usr/bin/perl

use constant 'WARNPERCENT'  => 65;
use constant 'ERRORPERCENT' => 80;

use strict;
use warnings;
use open ':std', ':encoding(UTF-8)';

use DateTime;
use Capture::Tiny(qw/capture/);

use lib '/app/tools/common/lib';
use Common::Session;
use Common::DatePeriod;
use Common::Amazon::Mail;

my $dbx = Common::Session::getdbx('admindb');
my $hosts = $dbx->resultset('Report::DAwsHost')->search( { 'check_cpu_usage' => 1 } );

## use the same minute for all hosts - ssh might take a bit
## so we don't want the machien to determine the minute id
my $minute_id = Common::DatePeriod::getMinuteId;

while ( my $host = $hosts->next ) {
    my $cmd = "ssh " . $host->hostname . " \"mpstat\"";
    my ( $stdin, $stderr, $exit ) = capture { system $cmd };
    if ($exit) {
        logMessage( 'error', $stderr );
    } else {
        my $data = {
            'cpu_idle' => ( split " ", ( split "\n", $stdin )[3] )[11],
            'd_aws_host_id' => $host->d_aws_host_id,
            'd_minute_id'   => $minute_id
        };
        my $row = $dbx->resultset('Report::SysCpuUsage')->update_or_create( $data, { 'key' => 'uidx_host_minute' } );
        my $x;
    }
}
