rblanche: add support for -c (chpobox)
[user/alex/software/my-snippets.git] / rblanche.py
1 #!/usr/bin/python
2 import optparse
3 import sys
4
5 import moira
6
7 def get_members_of_list(lst):
8     return moira.query('get_members_of_list', lst)
9
10 class RBlanche(object):
11     def __init__(self, chpoboxing=False, ):
12         self.reset_caches()
13         self.chpoboxing = chpoboxing
14
15     def reset_caches(self, ):
16         self.cache = {}
17         self.chpobox = {}
18
19     def expand(self, lst):
20         if lst in self.cache: return self.cache[lst]
21         try:
22             members = get_members_of_list(lst)
23         except moira.MoiraException, e:
24             code, message = e
25             if message == "Insufficient permission to perform requested database access":
26                 self.cache[lst] = [{'member_type': 'ERR', 'member_name':'** Error: no permissions to look up this list **'}]
27                 return self.cache[lst]
28             else: raise
29         for member in members:
30             if member['member_type'] == 'LIST':
31                 member['members'] = self.expand(member['member_name'])
32         self.cache[lst] = members
33         return members
34
35     def get_and_format_pobox(self, user):
36         result = moira.query('get_pobox', user)[0]
37         if result['type'] == 'SMTP':
38             fmt = '-> %s'
39         elif result['type'] == 'SPLIT':
40             fmt = '=> %s'
41         elif result['type'] in ('EXCHANGE', 'IMAP', 'POP', ''):
42             fmt = '  (%s)'
43         else:
44             raise ValueError("Unknown pobox type %s" % (result['type'], ))
45         text = ('%8s ' + fmt) % (result['login'], result['address'], )
46         return text
47
48     def format_user(self, user):
49         text = user
50         if self.chpoboxing:
51             if user not in self.chpobox:
52                 self.chpobox[user] = self.get_and_format_pobox(user)
53             text = self.chpobox[user]
54         return text
55
56     def print_tree(self, path, lst_tree):
57         for member in lst_tree:
58             if 'members' in member:
59                 path.append(member['member_name'])
60                 self.print_tree(path, member['members'])
61                 path.pop()
62             else:
63                 if member['member_type'] == "USER":
64                     text = self.format_user(member['member_name'])
65                 elif member['member_type'] == "ERR":
66                     text = member['member_name']
67                 else:
68                     text = "%s:%s" % (member['member_type'], member['member_name'], )
69                 print ":  ".join(path+[text])
70
71     def rblanche(self, lst):
72         result = self.expand(lst)
73         self.print_tree([lst], result)
74
75 def parse_args():
76     parser = optparse.OptionParser(usage='usage: %prog [--auth=yes|no|try] [-cd] list')
77     parser.add_option('--auth', dest='auth', default=None,
78                 help='authenticate to the moira server? (yes, no, or try)'
79     )
80     parser.add_option('-c', '--chpobox',
81                 dest='chpoboxing', action='store_true', default=False,
82                 help='check mail forwarding for each user',
83     )
84     options, args = parser.parse_args()
85
86     if len(args) != 1:
87         parser.error("incorrect number of arguments")
88
89     if options.auth:
90         if options.auth == 'yes': options.auth = True
91         elif options.auth == 'try': options.auth = None
92         elif options.auth == 'no': options.auth = False
93         else:
94             parser.error("--auth takes yes, no, and try (default; auth if possible)")
95
96     return options, args
97
98 if __name__ == '__main__':
99     options, args = parse_args()
100     moira.connect()
101     if options.auth:
102         moira.auth('rblnchpy')
103     elif options.auth is None:
104         try:
105             moira.auth('rblnchpy')
106         except moira.MoiraException:
107             print >>sys.stderr, "Warning: Failed to authenticate to moira"
108     rblanche = RBlanche(chpoboxing=options.chpoboxing)
109     rblanche.rblanche(args[0])