#!/usr/bin/perl

use constant 'MNTMYSQL' => '/mnt/mysql/';

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

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

my $mountPoints = {
    'RootUsage'     => '/',
    'DBDataUsage'   => MNTMYSQL . 'data',
    'DBBinlogUsage' => MNTMYSQL . 'binlog',
    'DBBackupUsage' => MNTMYSQL . 'backup',
};

my $id   = get 'http://169.254.169.254/latest/meta-data/instance-id';
my $ii   = [ capture { system("aws ec2 describe-instances --profile ec2cron --instance-ids $id") } ];
my $href = JSON::XS::decode_json( $ii->[0] );

my $name;
map { $name = $_->{'Value'} if $_->{'Key'} eq 'Name' } @{ $href->{'Reservations'}->[0]->{'Instances'}->[0]->{'Tags'} };
die "No name in tags for instances " if not defined $name;

my $jsonInput = { 'Namespace' => 'RSDisk' };
foreach my $metric ( sort keys %{$mountPoints} ) {
    my $mountPoint = $mountPoints->{$metric};
    next if not -e $mountPoint;

    my $capture = [ capture { system("df --output=pcent $mountPoint|tail -n+2|tr -d '% \n'") } ];
    if ( $capture->[1] ) {
        chomp $capture->[1];
        print $capture->[1] . "\n";
        next;
    }

    my $href = {
        'MetricName' => $metric,
        'Unit'       => 'Percent',
        'Value'      => $capture->[0] * 1
    };
    push @{ $href->{'Dimensions'} }, { 'Name' => 'InstanceId',   'Value' => $id };
    push @{ $href->{'Dimensions'} }, { 'Name' => 'InstanceName', 'Value' => $name };

    push @{ $jsonInput->{'MetricData'} }, $href;

}

my $aws_capture = [ capture { system( "aws cloudwatch put-metric-data --cli-input-json '" . encode_json($jsonInput) . "'" ) } ];
if ( $aws_capture->[2] ) {
    chomp $aws_capture->[1];
    print $aws_capture->[1] . "\n";
}
