Merge passwordless export fix
[mirror/userdir-ldap.git] / ud-forwardlist
1 #!/usr/bin/env python
2 # -*- mode: python -*-
3 # This script takes a list of .forward files and generates a list of colon
4 # delimited fields for import into a ldap directory. The fields represent
5 # the user and their email forwarding.
6 #
7 # A sample invokation..
8 #   cd /home
9 #   find -name ".foward" -maxdepth 2 | mkforwardlist | sort | less
10 # Then correct any invalid forward files if possible. After that stash the
11 # output in a file, remove the invalid lines and import it.
12 #
13 # It also understand .qmail type files
14
15 import re, time, getopt, os, sys, pwd, stat;
16
17 AddressSplit = re.compile("<(.*)>");
18
19 while (1):
20    File = sys.stdin.readline().strip()
21    if File == "":
22       break;
23
24    # Attempt to determine the UID   
25    try:
26       User = pwd.getpwuid(os.stat(File)[stat.ST_UID])[0];
27    except KeyError:
28       print "Invalid0", File;
29       continue;
30
31    # Read the first two non comment non empty lines
32    Forward = open(File,"r");
33    Line = None;
34    while (1):
35       Line2 = Forward.readline().strip()
36       if Line2 == "":
37          break;
38       if Line2[0] == '#' or Line2[0] == '\n':
39          continue;
40       if Line == None:
41          Line = Line2;
42       else:
43          break;
44
45    # If we got more than one line or no lines at all it is invalid
46    if Line == None or Line == "" or Line2 != "":
47       print "Invalid1", File;
48       continue;
49
50    # Abort for funky things like pipes or directions to mailboxes
51    if Line[0] == '/' or Line[0] == '|' or Line[0] == '.' or Line[-1] == '/' or \
52       Line.find('@') == -1:
53       print "Invalid2", File;
54       continue;
55
56    # Split off the address part
57    Address = AddressSplit.match(Line);
58    if Address == None: 
59       # Or parse a qmail adddress..
60       Address = Line;
61       if Address[0] == '&':
62          Address = Address[1:];
63
64    if Address == "":
65       print "Invalid3", File;
66       continue;
67
68    print User + ":",Address;