#!/usr/bin/env python

# Copyright (c) 2014 Anchor Systems

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

"""
NAME

    es-delete-index - delete an Elasticsearch index


SYNOPSIS

    es-delete-index <index> [HOST[:PORT]]


DESCRIPTION

    Connect to the ElasticSearch HTTP server at HOST:PORT (defaults to 
    localhost:9200), and submit a synchronous API request to delete the
    specified index.
"""

DEFAULT_HOST = "localhost"
DEFAULT_PORT = 9200

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

logger = logging.getLogger(__name__)

def main(argv=None):
    host = DEFAULT_HOST
    port = DEFAULT_PORT

    args = sys.argv
 
    if not len(args) >= 2:
        parser.print_usage()
        return 3
    index = args[1]
    
    try:
        address = args[2]
    except IndexError:
        pass
    else:
        if address.find(":") == -1:
            host = address
        else:
            host, port = address.split(":")
            try:
                port = int(port)
            except ValueError:
                parser.print_usage()
                return 2

    logger.info("Deleting index %s." % index)

    with Connection(host, port) as conn:
        resp = conn.delete('/%s/' % index)

    logger.info("Deleted index %s." % index)

    return 0

if __name__ == '__main__':
    hostname = socket.gethostname()
    fmt = ('[%s] [%%(process)d]: [%%(levelname)s] '
           '%%(message)s' % hostname)
    logging.basicConfig(level=logging.INFO, format=fmt)

    sys.exit(main(sys.argv))
