#!/usr/bin/env python

import argparse
import pkg_resources
import sys

from garbagedog.event_processor import GCEventProcessor


parser = argparse.ArgumentParser(description='Parse JVM gc.logs and emit stats over dogstatsd',
                                 usage="garbagedog --log-dir /var/log/eero/")

parser.add_argument('--tags',
                    help='Extra datadog tags, comma separated; ie "application:actorcluster, version:2017.07.27"')

parser.add_argument('--dogstatsd-host',
                    help='dogstatsd host (default: %(default)s)', default='localhost')

parser.add_argument('--dogstatsd-port', type=int,
                    help='dogstatsd port (default: %(default)s)', default=8125)

parser.add_argument('--verbose', action='store_true',
                    help='Emit noisy messages on stdout')

parser.add_argument('--log-dir',
                    help='Read from this log dir instead of stdin')

parser.add_argument('--glob-pattern',
                    help='Glob pattern to select gc.log files (default: %(default)s)', default="gc.log*")

parser.add_argument('--refresh-logfiles-seconds', type=int,
                    help='How often to recheck --log-dir if there are no logfiles found '
                         'or no new loglines have been written (default: %(default)s)', default=60)

parser.add_argument('--sleep-seconds', type=int,
                    help='How long to sleep between checking the logfile for new lines (default: %(default)s)',
                    default=1)


parser.add_argument("--version", "-v", help="Print version information", action='store_true')


args = parser.parse_args()

if args.version:
    version = pkg_resources.require("garbagedog")[0].version
    print("garbagedog {}".format(version))
    sys.exit(0)

parsed_tags = []
if args.tags:
    parsed_tags = args.tags.replace(' ', '').split(',')

gc_event_processor = GCEventProcessor(args.dogstatsd_host, args.dogstatsd_port, parsed_tags, args.verbose)
try:
    if args.log_dir:
        gc_event_processor.process_log_directory(args.log_dir,
                                                 glob_pattern=args.glob_pattern,
                                                 refresh_logfiles_seconds=args.refresh_logfiles_seconds,
                                                 sleep_seconds=args.sleep_seconds)
    else:
        gc_event_processor.process_stdin()
except KeyboardInterrupt:
    pass
