#!/usr/bin/perl

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

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

my ( $opt, $usage ) = clopt(
    [ 'prefix|p=s' => 'Prefix for the alarms to remove', { 'required' => 1 } ],
    [ 'match|m=s'  => 'Match parts of the alarm name' ],
    [ 'help|?|h'   => "print usage message and exit" ]
);

my $capture = runcmd( 'aws cloudwatch describe-alarms --alarm-name-prefix "' . $opt->prefix . '"' );
if ( $capture->[0] ) {
    my $aref = [ map { $_->{'AlarmName'} } @{ decode_json( $capture->[0] )->{'MetricAlarms'} } ];

    my $href;
    if ( $opt->match ) {
        my $match = quotemeta $opt->match;
        foreach my $name ( @{$aref} ) {
            next if not $name =~ m/.*$match.*/;
            push @{ $href->{'AlarmNames'} }, $name;
        }
    } else {
        $href = { 'AlarmNames' => $aref };
    }
    my $json = encode_json($href);

    map { print "Removing $_\n" } @{ $href->{'AlarmNames'} };

    my $file = '/tmp/remove_alarms.json';
    my $fh = FileHandle->new( $file, 'w' );
    $fh->print($json);
    $fh->close;

    my $aws_capture = runcmd( 'aws cloudwatch delete-alarms --cli-input-json file://' . $file );
    unlink $file if not $aws_capture->[2];
}

