#!/usr/bin/env python

# Author: Mike Babineau <mikeb@ea2d.com>
# Copyright 2011 Electronic Arts Inc.
# 
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# 
#     http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


import os, sys
import optparse, pprint

import loggly


ATTRIBUTES = ('created', 
              'description', 
              'discover', 
              'discover_time', 
              'id', 
              'name', 
              'port',
              'service',
              'service.display',
              'service.name')

FORMATS = ('raw', 'parse')


class Usage(Exception):
  def __init__(self, msg):
      self.msg = msg

def print_attribute(d, attribute):
    attr_list = attribute.split('.')
    attr = attr_list.pop(0)
    while len(attr_list) > 0:
        d = d[attr]
        attr = attr_list.pop(0)
    
    print d[attr]
    return

def print_parseable_dict(d, prefix=None):
    for key in d.keys():
        if type(d[key]) == dict:
            print_parseable_dict(d[key], key)
        else:
            if prefix:
                print "%s.%s=%s" % (prefix, key, d[key])
            else:
                print "%s=%s" % (key, d[key])
    return


def main(argv=None):
    parser = optparse.OptionParser()
    parser.add_option("-i", "--input-name", dest="name", help='(required) input name')
    parser.add_option("-a", "--attribute", dest="attribute", help='which attribute to return (created|description|discover|discover_time|id|name|port|service)')
    parser.add_option("-f", "--format", dest="format", help='if no attribute specified, how to format the output (raw|parse) (default is parse(able))')
    parser.add_option("-U", "--username", dest="username", help='loggly username')
    parser.add_option("-P", "--password", dest="password", help='loggly password')
    parser.add_option("-D", "--domain", dest="domain", help='customer-specific loggly domain (e.g., "acme.loggly.com")')
    (options, args) = parser.parse_args()
    
    # Arg validation
    try:
        if options.name:
            name = options.name
        else:
            raise Usage("No input name specified")
        
        if options.attribute:
            if options.attribute in ATTRIBUTES:
                attribute = options.attribute
            else:
                raise Usage("Attribute must be one of (%s)" % '|'.join(ATTRIBUTES))
        else:
            attribute = None
        
        if options.format:
            if options.format in FORMATS:
                format = options.format
            else:
                raise Usage("Format must be one of (%s)" % '|'.join(FORMATS))
        else:
            format = 'parse'
        
        if options.username:
            username = options.username
        else:
            if 'LOGGLY_USERNAME' in os.environ:
                username = os.environ['LOGGLY_USERNAME']
            else:
                raise Usage("No username passed, and LOGGLY_USERNAME environment variable not set")

        if options.password:
            password = options.password
        else:
            if 'LOGGLY_PASSWORD' in os.environ:
                password = os.environ['LOGGLY_PASSWORD']
            else:
                raise Usage("No password passed, and LOGGLY_PASSWORD environment variable not set")
        
        if options.domain:
            domain = options.domain
        else:
            if 'LOGGLY_DOMAIN' in os.environ:
                domain = os.environ['LOGGLY_DOMAIN']
            else:
                raise Usage("No domain passed, and LOGGLY_DOMAIN environment variable not set")
                
    except Usage, err:
        print >> sys.stderr, sys.argv[0].split("/")[-1] + ": " + str(err.msg)
        print >> sys.stderr, "\t for help use --help"
        return 2
    
    c = loggly.LogglyConnection(username, password, domain)
    result = c.get_all_inputs([name])

    if len(result) == 0:
        print "Error: Input \"%s\" not found" % name
        return 1
    elif len(result) > 1:
        print "Error: More than one input found.  No action taken"
        return 1
    else:
        input = result[0]

    if attribute:
        print_attribute(input.__dict__, attribute)
        return 0
    else:
        if format == 'raw':
            print input.__dict__
            return 0
        if format == 'parse':
            print_parseable_dict(input.__dict__)
            return 0
            


if __name__ == "__main__":
    sys.exit(main())
    