#!/usr/bin/env python

import ldap, sys

searchfilter = "cn=%s" % (sys.argv[1])
if len(sys.argv) > 2:
	for args in sys.argv[2:]:
		searchfilter = "%s %s" % (searchfilter, args)

LDAPURL = "ldap://ldap.ntnu.no"
basedns = ["dc=NTNU,dc=NO", "dc=SINTEF,dc=NO", "dc=HiST,dc=NO",
	"dc=Andre,dc=NO"]
searchscope = ldap.SCOPE_SUBTREE
retrieveattributes = ['mail', 'telephoneNumber', 'cn']

try:
	l = ldap.initialize(LDAPURL)
	l.simple_bind_s("","")
	records = []
	for basedn in basedns:
		result = l.search_s(basedn, ldap.SCOPE_SUBTREE, searchfilter, 
						retrieveattributes)
		records = records + result
except ldap.LDAPError, e:
	print e
	l.unbind_s()
	sys.exit(1)

if len(records) < 1:
	print "No matches"
	l.unbind_s()
	sys.exit(1)

print "Found %i matches..." % (len(records))
for record in records:
	mail = ' '
	tel = ' '
	if record[1].has_key('mail'):
		mail = record[1]['mail'][0]
	if record[1].has_key('telephoneNumber'):
		tel = record[1]['telephoneNumber'][0]
	name = unicode(record[1]['cn'][0], 'utf-8').encode('latin-1')
	print "%s\t%s\t%s" % (mail, name, tel)
l.unbind_s()
sys.exit(0)

