#!/usr/bin/python2.6
#
# Copyright (c) 2011 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.
#

import getopt, sys, os, time
from coils.foundation    import ldap_paged_search, LDAPConnectionFactory
from coils.core          import *
try:
    import ldap
except:
    print('LDAP support not available in current environment.')
    sys.exit(1)

def usage():
    print """
Test the operation of a DSA connection defined via OIELDAPSources.

    --name=   The "name" of the DSA connection.
    --base=   The search root for the test query.
    --filter= The LDAP filter used to query the connection.
    
    All three parameters are required.
    """
    return

def main(argv):

    timeout = 100
    count = 1

    # Process command line arguements
    if (len(argv) == 0):
        usage()
        sys.exit(2)
    try:
        opts, args = getopt.getopt(argv,
                                   "h:n:f:b:",
                                   ["help", "name=", "filter=", "base=" ])
    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 ('-f', '--filter')):
            filter = arg
        elif (opt in ('-n', '--name')):
            dsa_name = arg
        elif (opt in ('-b', '--base')):
            base = arg

    # Initialize COILs
    initialize_COILS({'log_file': '{0}/coils.log'.format(os.getenv('HOME'))})

    dsa = LDAPConnectionFactory.Connect(dsa_name)
    print('Connected to DSA "{0}"'.format(dsa_name))
    print('  Search Filter: "{0}"'.format(filter))
    print('  Search Root:   "{0}"'.format(base))
    results = ldap_paged_search(connection    = dsa,
                                attributes    = ['dn'],
                                search_filter = filter,
                                search_base   = base)
    print('Retrieved {0} results.'.format(len(results)))
                                
    dsa.unbind()

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