#!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# |             ____ _               _        __  __ _  __           |
# |            / ___| |__   ___  ___| | __   |  \/  | |/ /           |
# |           | |   | '_ \ / _ \/ __| |/ /   | |\/| | ' /            |
# |           | |___| | | |  __/ (__|   <    | |  | | . \            |
# |            \____|_| |_|\___|\___|_|\_\___|_|  |_|_|\_\           |
# |                                                                  |
# | Copyright Mathias Kettner 2018             mk@mathias-kettner.de |
# +------------------------------------------------------------------+
#
# This file is part of Check_MK.
# The official homepage is at http://mathias-kettner.de/check_mk.
#
# check_mk is free software;  you can redistribute it and/or modify it
# under the  terms of the  GNU General Public License  as published by
# the Free Software Foundation in version 2.  check_mk is  distributed
# in the hope that it will be useful, but WITHOUT ANY WARRANTY;  with-
# out even the implied warranty of  MERCHANTABILITY  or  FITNESS FOR A
# PARTICULAR PURPOSE. See the  GNU General Public License for more de-
# tails. You should have  received  a copy of the  GNU  General Public
# License along with GNU Make; see the file  COPYING.  If  not,  write
# to the Free Software Foundation, Inc., 51 Franklin St,  Fifth Floor,
# Boston, MA 02110-1301 USA.


def check_aws_ec2_summary(item, params, parsed):
    instances_by_state = {}
    long_output = []
    for instance in parsed:
        instance_private_dns_name = instance['PrivateDnsName']
        instance_id = instance['InstanceId']
        instance_state = instance['State']['Name']
        instances_by_state.setdefault(instance_state, []).append(instance_id)

        long_output_info = [
            "[%s] %s: %s" % (instance_id, instance_private_dns_name, instance_state)
        ]
        tags = _extract_aws_ec2_tags(instance)
        if tags:
            long_output_info.append("[Tags] %s" % tags)
        long_output.append(", ".join(long_output_info))

    yield 0, "Instances: %s" % sum([len(v) for v in instances_by_state.itervalues()])
    for instance_state, instances in instances_by_state.iteritems():
        yield 0, "%s: %s" % (instance_state, len(instances))

    if long_output:
        yield 0, "\n%s" % "\n".join(long_output)


def _extract_aws_ec2_tags(metrics):
    # metrics is dict with key 'Tags'
    return ", ".join(["%s: %s" % (pair['Key'], pair['Value']) for pair in metrics.get('Tags', [])])


check_info['aws_ec2_summary'] = {
    'parse_function': parse_aws,
    'inventory_function': discover_single,
    'check_function': check_aws_ec2_summary,
    'service_description': 'AWS/EC2 Summary',
    'includes': ['aws.include'],
}
