Add README with license and ~history
[user/alex/software/my-snippets.git] / card-access
1 #!/usr/bin/python
2
3 import sys
4 import os
5 import csv
6 import subprocess
7 import ldap
8
9 #columns = [ 'timestamp', 'first', 'last', 'email', 'constituency', 'year', 'major', 'cell', 'mitid', 'retreat', 'whynot', 'project', 'othermit', ]
10 format = "%(first_with_initial)s;%(last_canonical)s;%(mitid)s"
11
12 def dictize_line(header, line,):
13     line_dict = {}
14     for key, elem in zip(header, line, ):
15         line_dict[key]=elem
16     return line_dict
17
18
19
20 def get_ldap_data(username, fields):
21     con = ldap.open('ldap.mit.edu')
22     con.simple_bind_s("", "")
23     dn = "dc=mit,dc=edu"
24     result = con.search_s('dc=mit,dc=edu', ldap.SCOPE_SUBTREE, 'uid=%s'%username, fields)
25     if len(result) > 1: print "WARNING: More than one result returned for %s" % username
26     if len(result) < 1: print "WARNING: Only one result returned for %s" % username
27     ret = {}
28     for key in result[0][1]:
29         ret[key] = result[0][1][key][0]
30     return ret
31
32 def get_data_dict(line_dict):
33     email = line_dict['email']
34     username = email.lower().replace('@mit.edu', '')
35     ldap = get_ldap_data(username, [ 'cn' , 'sn' , 'givenName' ])
36     first = ldap['givenName'].replace(' ', '_').upper()
37     last = ldap['sn'].replace(' ', '_').upper()
38     mitid = line_dict['mitid']
39     data_dict = { 'first_with_initial': first, 'last_canonical': last, 'mitid': mitid }
40     return data_dict
41     
42 def format_line(data_dict):
43     return format % data_dict
44     
45
46 def do_produce_card_info(db = sys.stdin):
47     reader = csv.reader(db, )
48     lines = []
49
50     header = reader.next()
51     line_dict = dictize_line(header, header, )
52     data_dict = { 'first_with_initial': 'FIRST_M', 'last_canonical': 'LASTNAME', 'mitid': 'MIT ID' }
53     lines.append(format_line(data_dict))
54
55     for line in reader:
56         line_dict = dictize_line(header, line)
57         print line_dict
58         lines.append(format_line(get_data_dict(line_dict)))
59     print '\n'.join(lines)
60
61 if __name__== '__main__':
62     do_produce_card_info()