#!/usr/bin/perl

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

use JSON::XS;
use LWP::Simple;
use Capture::Tiny(qw/capture/);

use lib '/app/tools/common/lib';
use Common::Session;

## avoid 00:00 minute switch over seconds between NOW() and heartbeat
sleep 15;

my $dbxAdmin  = Common::Session::getdbx('admindb');
my $dbhMaster = Common::Session::getdbh('dbmaster');

my $jsonInput;
my $rows = $dbhMaster->selectall_arrayref(qq{ SELECT hostname, SECOND(NOW()) - SECOND(heartbeat) FROM RSCOMMON.job_host });
foreach my $row ( @{$rows} ) {
    my ( $host, $secsBehind ) = @{$row};

    my $dbHost = $dbxAdmin->resultset('Report::DAwsHost')->search( { 'hostname' => $host, 'state' => 'running' } )->first;
    if ( not defined $dbHost ) {
        logMessage( 'error', "$host is not in d_aws_host table on admin DB" );
        next;
    }

    my $id   = $dbHost->instance_id;
    my $name = $dbHost->hostname;

    my $data = {
        'MetricName' => 'JobHostHeartbeat',
        'Unit'       => 'Count',
        'Value'      => abs( $secsBehind * 1 )
    };
    push @{ $data->{'Dimensions'} }, { 'Name' => 'InstanceId',   'Value' => $id };
    push @{ $data->{'Dimensions'} }, { 'Name' => 'InstanceName', 'Value' => $name };
    push @{$jsonInput}, $data;

}

my $file = "/tmp/putJobHostHeartbeat.json";
my $json = encode_json($jsonInput);
my $fh   = FileHandle->new( $file, "w" );
$fh->print($json);
$fh->close;

my $aws_capture = [ capture { system("aws cloudwatch put-metric-data --namespace RSSystem --metric-data file://$file") } ];
if ( $aws_capture->[2] ) {
    chomp $aws_capture->[1];
    print $aws_capture->[1] . "\n";
} else {
    print Common::Session::mysql_now() . " " . $aws_capture->[2] . "\n";
    unlink $file;
}
