#!/usr/bin/perl

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

use JSON::XS;
use FileHandle;
use Types::Serialiser;
use Capture::Tiny(qw/capture/);
use Text::CSV::Easy(qw/csv_build csv_parse/);

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

my ( $opt, $usage ) = clopt(
    [ 'all|a'        => 'Register all production machines' ],
    [ 'instance|i=s' => 'EC2 instance to register' ],
    [ 'help|?|h'     => "print usage message and exit" ]
);
if ( $opt->help ) {
    logMessage( 'info', $usage->text, 'options' );
    exit 1;
}

my $dbx = Common::Session::getdbx('admindb');
my $dbh = Common::Session::getdbh('dbmaster');

my $rows;
if ( $opt->instance ) {
    my $rset = $dbx->resultset('Report::DAwsHost')->search( { 'hostname' => $opt->instance, 'state' => 'running' } );
    push @{$rows}, $rset->first if defined $rset;
} elsif ( $opt->all ) {
    my $hosts = $dbh->selectcol_arrayref('SELECT hostname FROM RSCOMMON.job_host');
    foreach my $host ( @{$hosts} ) {
        my $rset = $dbx->resultset('Report::DAwsHost')->search( { 'hostname' => $host, 'state' => 'running' } );
        push @{$rows}, $rset->first if defined $rset;
    }
} else {
    logMessage( 'info', $usage->text, 'options' );
    exit 1;
}

foreach my $row ( @{$rows} ) {
    my $id   = $row->instance_id;
    my $host = $row->hostname;

    my $alarmref = getref();
    $alarmref->{'Dimensions'}       = [ { 'Name' => 'InstanceId', 'Value' => $id }, { 'Name' => 'InstanceName', 'Value' => $host } ];
    $alarmref->{'AlarmDescription'} = "JobHost Heartbeat - $host";
    $alarmref->{'AlarmName'}        = "JobHost Heartbeat - $host";

    my $file = "/tmp/$host.json";
    my $json = JSON::XS::encode_json($alarmref);
    my $fh   = FileHandle->new( $file, 'w' );
    $fh->print($json);
    $fh->close;

    my $command = 'aws cloudwatch put-metric-alarm --cli-input-json file://' . $file;
    print "$command\n";

    my $capture = [ capture { system($command) } ];
    unlink $file if not $capture->[2];

}

sub getref {
    {
        'AlarmDescription'   => undef,
        'AlarmName'          => undef,
        'Dimensions'         => undef,
        'AlarmActions'       => ['arn:aws:sns:us-west-2:290365479392:DB_Alerts'],
        'ActionsEnabled'     => Types::Serialiser::true,
        'ComparisonOperator' => 'GreaterThanOrEqualToThreshold',
        'DatapointsToAlarm'  => 2,
        'EvaluationPeriods'  => 2,
        'MetricName'         => 'JobHostHeartbeat',
        'Namespace'          => 'RSSystem',
        'Period'             => 60,
        'Statistic'          => 'Average',
        'Threshold'          => 900,
        'TreatMissingData'   => 'missing',
    };
}
