#!/usr/bin/env python
########################################
#
# alert-query - Alert Query tool
#
########################################

import os
import sys
import argparse

possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]),
                                                os.pardir,
                                                os.pardir))
if os.path.exists(os.path.join(possible_topdir, 'alerta', '__init__.py')):
    sys.path.insert(0, possible_topdir)

from alerta.common import config, status_code, severity_code
from alerta.common import log as logging
from alerta.query.client import QueryClient, Version

LOG = logging.getLogger('alerta.query')
CONF = config.CONF


def main():

    try:
        parser = argparse.ArgumentParser(
            add_help=False,
            description="Alert database query tool - show alerts filtered by attributes",
            epilog="alert-query.py --color --env QA,REL --group Puppet --count 10 --show all"
        )
        parser.add_argument(
            "--minutes",
            "--mins",
            type=int,
            dest="minutes",
            default=0,
            help="Show alerts for last <x> minutes"
        )
        parser.add_argument(
            "--hours",
            "--hrs",
            type=int,
            dest="hours",
            default=0,
            help="Show alerts for last <x> hours"
        )
        parser.add_argument(
            "--days",
            type=int,
            dest="days",
            default=0,
            help="Show alerts for last <x> days"
        )
        parser.add_argument(
            "-i",
            "--id",
            action="append",
            dest="alertid",
            help="Alert ID (can use 8-char abbrev id)"
        )
        parser.add_argument(
            "-E",
            "--environment",
            metavar='ENV',
            action="append",
            dest="environment",
            help="Environment eg. production, development"
        )
        parser.add_argument(
            "--not-environment",
            metavar='ENV',
            action="append",
            dest="not_environment"
        )
        parser.add_argument(
            "-S",
            "--svc",
            "--service",
            action="append",
            dest="service",
            help="Service eg. R1, R2, Discussion, ContentAPI, Frontend, " +
                 "FlexibleContent, Identity, Mobile, Soulmates, MicroApp, " +
                 "Mutualisation, SharedSvcs, Network, Infrastructure"
        )
        parser.add_argument(
            "--not-service",
            metavar='SERVICE',
            action="append",
            dest="not_service"
        )
        parser.add_argument(
            "-r",
            "--resource",
            action="append",
            dest="resource",
            help="Resource under alarm eg. hostname, network device, application"
        )
        parser.add_argument(
            "--not-resource",
            metavar='RESOURCE',
            action="append",
            dest="not_resource"
        )
        parser.add_argument(
            "-s",
            "--severity",
            action="append",
            dest="severity",
            help="Severity eg. %s" % ','.join(severity_code.ALL)
        )
        parser.add_argument(
            "--not-severity",
            metavar='SEVERITY',
            action="append",
            dest="not_severity"
        )
        parser.add_argument(
            "--status",
            action="append",
            dest="status",
            help="Status eg. %s" % ','.join(status_code.ALL)
        )
        parser.add_argument(
            "--not-status",
            metavar='STATUS',
            action="append",
            dest="not_status"
        )
        parser.add_argument(
            "-e",
            "--event",
            action="append",
            dest="event",
            help="Event name eg. HostAvail, PingResponse, AppStatus"
        )
        parser.add_argument(
            "--not-event",
            metavar='EVENT',
            action="append",
            dest="not_event"
        )
        parser.add_argument(
            "-g",
            "--group",
            action="append",
            dest="group",
            help="Event group eg. Application, Backup, Database, HA, " +
                 "Hardware, System, OS, Performance, Storage, Security, Web"
        )
        parser.add_argument(
            "--not-group",
            metavar='GROUP',
            action="append",
            dest="not_group"
        )
        parser.add_argument(
            "--origin",
            action="append",
            dest="origin",
            help="Origin of the alert eg. alert-sender, alert-ganglia"
        )
        parser.add_argument(
            "--not-origin",
            metavar='ORIGIN',
            action="append",
            dest="not_origin"
        )
        parser.add_argument(
            "-v",
            "--value",
            action="append",
            dest="value",
            help="Event value eg. 100%%, Down, PingFail, 55tps, ORA-1664"
        )
        parser.add_argument(
            "--not-value",
            metavar='VALUE',
            action="append",
            dest="not_value"
        )
        parser.add_argument(
            "-T",
            "--tags",
            action="append",
            dest="tags",
            help="List of tags eg. os:Linux, region:eu-west-1"
        )
        parser.add_argument(
            "--not-tags",
            metavar='TAGS',
            action="append",
            dest="not_tags"
        )
        parser.add_argument(
            "-A",
            "--attributes",
            action="append",
            dest="attributes",
            help="List of attributes eg. Key=value"
        )
        parser.add_argument(
            "--not-attributes",
            metavar='ATTRIBUTES',
            action="append",
            dest="not_attributes"
        )
        parser.add_argument(
            "-t",
            "--text",
            action="append",
            dest="text"
        )
        parser.add_argument(
            "--not-text",
            metavar='TEXT',
            action="append",
            dest="not_text"
        )
        parser.add_argument(
            "--type",
            action="append",
            dest="event_type",
            help="Event type eg. snmptrapAlert, syslogAlert"
        )
        parser.add_argument(
            "--not-type",
            metavar='TYPE',
            action="append",
            dest="not_event_type"
        )
        parser.add_argument(
            "--repeat",
            action="store",
            choices=['true', 'false'],
            dest="repeat"
        )
        parser.add_argument(
            "--show",
            action="append",
            dest="show",
            default=[],
            help="Show 'text', 'summary', 'times', 'attributes', 'details', 'tags', 'raw', 'history', 'counts' and 'color'"
        )
        parser.add_argument(
            "--oneline",
            action="store_true",
            dest="oneline",
            default=False,
            help="Shorthand for \"--format '{i} {rd} {sa} {E} {S} {r} {g} {e} {v} {t}'\""
        )
        parser.add_argument(
            "--date",
            dest="date",
            default="local",
            help="Date format of 'relative', 'local', 'iso', 'rfc', 'short' or 'raw'"
        )
        parser.add_argument(
            "--format",
            dest="format",
            help="Format allows you to specify which information you want to show."
        )
        parser.add_argument(
            "-o",
            "--orderby",
            "--sortby",
            "--sort-by",
            dest="sortby",
            default='lastReceiveTime',
            help="Sort by attribute (default: createTime)"
        )
        parser.add_argument(
            "-w",
            "--watch",
            action="store_true",
            dest="watch",
            default=False,
            help="Periodically poll for new  alerts every 2 seconds."
        )
        parser.add_argument(
            "-n",
            "--interval",
            type=int,
            dest="interval",
            default=2,
            help="Change the default watch interval."
        )
        parser.add_argument(
            "--count",
            "--limit",
            type=int,
            dest="limit",
            default=0
        )
        parser.add_argument(
            "-q",
            "--query",
            dest="query",
            help="Mongo-compliant query. Must be valid JSON."
        )
        parser.add_argument(
            "--no-header",
            action="store_true",
            dest="noheader"
        )
        parser.add_argument(
            "--no-footer",
            action="store_true",
            dest="nofooter"
        )
        parser.add_argument(
            "-G",
            "--color",
            "--colour",
            action="store_true",
            default=False,
            help="Synonym for --show=color"
        )
        parser.add_argument(
            "--output",
            dest="output",
            default="text",
            help="Output format of 'text', 'table' or 'json'"
        )
        parser.add_argument(
            "-j",
            "--json",
            action="store_true",
            default=False,
            help="JSON formatted output"
        )
        parser.add_argument(
            "-K",
            "--ack",
            action="store_true",
            default=False,
            help="Ack alerts that match the query."
        )
        parser.add_argument(
            "-X",
            "--delete",
            action="store_true",
            default=False,
            help="Delete alerts that match the query. Use with caution."
        )
        parser.add_argument(
            "-d",
            "--dry-run",
            action="store_true",
            default=False,
            help="Do not run. Output query and filter."
        )

        config.parse_args(version=Version, cli_parser=parser, daemon=False)
        logging.setup('alerta')

        query = QueryClient()
        query.main()

    except Exception, e:
        print >> sys.stderr, e
        sys.exit(1)

if __name__ == '__main__':
    main()
