#!/usr/bin/env python

# Copyright (c) 2014 Anchor Systems

# https://github.com/anchor/elasticsearch-scripts

"""
NAME

    es-cluster-health - print the current state of /_cluster/health


SYNOPSIS

    es-cluster-health [HOST[:PORT]]


DESCRIPTION

    This command will always output JSON to standard output.

"""
DEFAULT_HOST = "localhost"
DEFAULT_PORT = 9200

from esadmin import Connection
import json
import logging
import os
import sys

logger = logging.getLogger(__name__)

def usage(argv):
    print >>sys.stderr, ("Usage:\n\t%s [HOST[:PORT]]\n" %
                         os.path.basename(argv[0]))

def main(argv=None):
    if argv is None:
        argv = sys.argv

    host = DEFAULT_HOST
    port = DEFAULT_PORT

    try:
        address = sys.argv[1]
    except IndexError:
        pass
    else:
        if address.find(":") == -1:
            host = address
        else:
            host, port = address.split(":")
            try:
                port = int(port)
            except ValueError:
                usage(argv)
                return 2

    with Connection(host, port) as conn:
        resp = conn.get('/_cluster/health')
        print json.dumps(resp, ensure_ascii=True, indent=2,
                         sort_keys=True)

    return 0

if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO,
                        format='%(levelname)s:\t%(message)s')

    sys.exit(main(sys.argv))
