#!/usr/bin/perl

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

use JSON::XS;
use FileHandle;
use Net::Amazon::EC2 0.36;

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

my $dbx = Common::Session::getdbx('admindb');
my $db_instances;
map { $db_instances->{ $_->instance_id }++ } $dbx->resultset('Report::DAwsHost')->all;

my ( $access, $secret, $region ) = get_aws_creds('sysec2');
$region = shift @ARGV || $region;

my $ec2 = Net::Amazon::EC2->new(
    'AWSAccessKeyId'    => $access,
    'SecretAccessKey'   => $secret,
    'signature_version' => 4,
    'region'            => $region
);

foreach my $reservation ( @{ $ec2->describe_instances } ) {
    foreach my $instance ( $reservation->instances_set ) {

        ## remove existing instances so we have a list of
        ## non-existant instances to set to terminated if
        ## they're no longer in the list of ec2 servers
        delete $db_instances->{ $instance->instance_id };

        my $net;
        if ( defined $instance->network_interface_set ) {
            $net = join "|||", map { $_->group_id . ":" . $_->group_name } @{ $instance->network_interface_set->[0]->group_sets };
        }

        my $created_at = $instance->launch_time;
        $created_at =~ s/[a-z]/ /ig;
        $created_at =~ s/(.*)\..*$/$1/ig;

        my $name  = $instance->tag_set->[0]->value;
        my $state = $instance->instance_state->name;

        my ( $is_production, $chk_disk_space, $chk_cpu_usage ) = ( undef, undef, undef );
        if ( $name =~ m/rpsdb|rpsapp|rpsweb|report|bpweb|dbcommon/ and $state eq 'running' ) {
            ( $is_production, $chk_disk_space, $chk_cpu_usage ) = ( 1, 1, 1 );
        }

        my $data = {
            'instance_id'      => $instance->instance_id,
            'hostname'         => $name,
            'instance_type'    => $instance->instance_type,
            'image_id'         => $instance->image_id,
            'zone'             => $instance->placement->availability_zone,
            'ip'               => $instance->ip_address,
            'private_ip'       => $instance->private_ip_address,
            'vpc_id'           => $instance->vpc_id,
            'subnet'           => $instance->subnet_id,
            'security_groups'  => $net,
            'state'            => $state,
            'is_production'    => $is_production,
            'check_disk_space' => $chk_disk_space,
            'check_cpu_usage'  => $chk_cpu_usage,
            'created_at'       => $created_at
        };

        my $row = $dbx->resultset('Report::DAwsHost')->find_or_create( $data, { 'key' => 'uidx_instance_id' } );
        if ( $row->state ne $state ) {
            $row->state($state);
            $row->updated_at( \'NOW()' );
            $row->update;
        }
    }
}

if ( scalar keys %{$db_instances} ) {
    foreach my $id ( sort keys %{$db_instances} ) {
        next unless $id;
        my $row = $dbx->resultset('Report::DAwsHost')->search( { 'instance_id' => $id } )->first;
        next if $row->state eq 'terminated';
        $row->state('terminated');
        $row->updated_at( \'NOW()' );
        $row->update;
    }
}
