#!/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

import loggly


SERVICES = ('syslogudp', 
            'syslogtcp', 
            'http', 
            'syslog_tls', 
            'syslogtcp_strip', 
            'syslogudp_strip')


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


def main(argv=None):
    parser = optparse.OptionParser()
    parser.add_option("-i", "--input-name", dest="name", help='(required) input name')
    parser.add_option("-s", "--service", dest="service", help="(required) input service (%s)" % '|'.join(SERVICES))
    parser.add_option("-j", "--description", dest="description", help='input description')
    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.service:
            if options.service in SERVICES:
                service = options.service
            else:
                raise Usage("Service must be one of (%s)" % '|'.join(SERVICES))
        else:
            raise Usage("No input service specified")
        
        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")
        
        description = options.description
        
    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)
    print "Creating input \"%s\" of type \"%s\"" % (name, service)
    
    # Support idempotence
    if name in c.list_inputs():
        print "Input already exists"
        return 0
    else:
        print c.create_input(name, service, description)
        return 0


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