#!/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 $rset;
if ( $opt->instance ) {
    $rset = $dbx->resultset('Report::DAwsHost')->search( { 'hostname' => $opt->instance, 'state' => 'running' } );
} elsif ( $opt->all ) {
    $rset = $dbx->resultset('Report::DAwsHost')->search( { 'is_production' => 1, 'state' => 'running' } );
} else {
    logMessage( 'info', $usage->text, 'options' );
    exit 1;
}

while ( my $row = $rset->next ) {
    my $id   = $row->instance_id;
    my $host = $row->hostname;

    my $alarmref = getref();
    $alarmref->{'Dimensions'}       = [ { 'Name' => 'InstanceId', 'Value' => $id } ];
    $alarmref->{'AlarmDescription'} = "High CPU Utilization - $host";
    $alarmref->{'AlarmName'}        = "High CPU Utilization - $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'  => 7,
        'EvaluationPeriods'  => 10,
        'MetricName'         => 'CPUUtilization',
        'Namespace'          => 'AWS/EC2',
        'Period'             => 60,
        'Statistic'          => 'Average',
        'Threshold'          => 85,
        'TreatMissingData'   => 'missing',
    };
}
