Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: ef889f719b
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 71 lines (57 sloc) 2.058 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
#!/usr/bin/python
"""
WMF mailadmin mbcleanup
Cleans up mailboxes for no longer existing accounts
Written by Mark Bergsma <mark@wikimedia.org>
"""

import sys, os, sqlite3, time

def get_accounts(dbname):
    """
Retrieves a list of current accounts
"""
    
    conn = sqlite3.connect(dbname)
    cur = conn.cursor()
    cur.execute("SELECT domain, localpart FROM account")
    
    return set(cur.fetchall())
    
def get_mailboxes(mbroot):
    """
Retrieves a list of mail boxes
"""
    
    # 2 levels: domain/localpart
    mailboxes = set()
    for domain in os.listdir(mbroot):
        domaindir = os.path.join(mbroot, domain)
        if not domain.startswith('.') and os.path.isdir(domaindir):
            try:
                for localpart in os.listdir(domaindir):
                    if not localpart.startswith('.') and localpart.find('@') < 0 and \
                        os.path.isdir(os.path.join(domaindir, localpart)):
                        mailboxes.add((unicode(domain), unicode(localpart)))
            except OSError, e:
                if e.errno != 13: raise

    return mailboxes

def move_mailboxes(mbroot, mbbackuproot, mailboxes):
    """
Moves a set of mailboxes to a backup location
"""
    
    for mb in mailboxes:
        date = time.strftime('%Y%m%d%H%M')
        oldpath = os.path.join(mbroot, mb[0], mb[1])
        newpath = os.path.join(mbbackuproot, mb[0], mb[1]) + '@' + date
        print 'Moving', oldpath, '=>', newpath
        os.makedirs(newpath)
        os.rename(oldpath, newpath)

def main():
    """
Main function
"""
    
    try:
        dbname, mbroot, mbbackuproot = sys.argv[1:4]
    except ValueError:
        print >> sys.stderr, "Usage:", sys.argv[0], "{user.db file} {mail boxes root path} {backup root path}"
        sys.exit(1)
        
    accounts, mailboxes = get_accounts(dbname), get_mailboxes(mbroot)
    
    # Move mailboxes without a corresponding account
    move_mailboxes(mbroot, mbbackuproot, mailboxes - accounts)

if __name__ == '__main__':
    main()
Something went wrong with that request. Please try again.