#!/usr/bin/python2.6
# Copyright (c) 2009, 2010 Adam Tauno Williams <awilliam@whitemice.org>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
from coils.core  import *
import getopt, sys, os

def usage():
    print """
        Test the authentication of a COILS account.
        --help          Display this message.
        --user=         Authentication name
        --password=     Authentication password
        --token=        Authentication token
    """
    return

def main(argv):
    # Process command line arguements
    command = None
    parameters = None
    options = { }
    metadata = { }
    metadata['authentication'] = { }
    metadata['authentication']['mechanism'] = 'anonymous'
    if (len(argv) == 0):
        usage()
        sys.exit(2)
    try:
        opts, args = getopt.getopt(argv,
                                   "hu:s:t:",
                                  ["help", "user=", "password=", "token="])
    except getopt.GetoptError, e:
        print e
        usage()
        sys.exit(2)
    for opt, arg in opts:
        if opt in ("-h", "--help"):
            usage()
            sys.exit(0)
        elif opt in ("-u", "--user"):
            metadata['authentication']['login'] = arg
        elif opt in ("-s", "--password"):
           if (metadata['authentication']['mechanism'] == 'TOKEN'):
                print 'Token alread specified, ignoring password'
           else:
                metadata['authentication']['mechanism'] = 'PLAIN'
                metadata['authentication']['secret'] = arg
        elif opt in ("-t", "--token"):
            if (metadata['authentication']['mechanism'] == 'PLAIN'):
                print 'Password alread specified, ignoring token'
            else:
                metadata['authentication']['mechanism'] = 'TOKEN'
                metadata['authentication']['token'] = arg

    # Initialize COILs
    initialize_COILS({'log_file': '{0}/coils.log'.format(os.getenv('HOME'))})
    if (metadata['authentication']['mechanism'] == 'anonymous'):
        print 'Testing anonymous authentication'
        ctx = AnonymousContext(metadata)
    else:
        print 'Testing %s authentication mechanism' % metadata['authentication']['mechanism']
        try:
            ctx = AuthenticatedContext(metadata)
        except Exception, e:
            print 'Authentication failure'
            print e
            sys.exit(1)
    print 'Authentication success'
    sys.exit(0)

if __name__ == "__main__":
    main(sys.argv[1:])
