#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from collections import defaultdict
import requests

url = 'http://localhost:9200/_cluster/health'
headers = {
    'Content-Type': 'application/json; charset=utf-8'
}

def main():
    try:
        result = requests.get(url=url, headers=headers)
        if result.json() is not None:
            json_response = result.json()
            if 'status' not in json_response:
                print('CRIT - Received invalid JSON response from server: "%s"'
                                 % json_response)
                exit(2)
            states = defaultdict(None, {
                'green': {
                    'level': 'OK',
                    'code': 0
                },
                'yellow': {
                    'level': 'WARN',
                    'code': 1
                },
                'red': {
                    'level': 'CRIT',
                    'code': 2
                }
            })
            state = states.get(json_response['status'])
            print('%s - Cluster status is "%s"' % (state['level'],
                                                   json_response['status']))
            exit(state['code'])
        print('CRIT - Received invalid response from '
              'ElasticSearch http server: %s' % result)
        exit(2)
    except requests.ConnectionError:
        print('CRIT - ElasticSearch is down')
        exit(2)


if __name__ == '__main__':
    main()
