#!/home/okin/bin/python

"""
Whitelist management.  Usage:

    whitelist.py -s whitelistpath
    
        Reads e-mails from stdin and adds to the file at whitelistpath.
        
    whitelist.py -d whitelistpath
    
        Reads e-mails from stdin and deletes from the file at whitelistpath.
        
    whitelist.py whitelistpath
    
        Filters an e-mail: adds the header "X-SCF-Whitelist: YES" if the From address of the sender
        matches a whitelist entry, and "X-SCF-Whitelist: NO" otherwise. A whitelist entry is considered
        to match if it is contained anywhere in the message From header.
"""

# Note: in Python 2.3 (which is running on scf), module
# was called email.Generator.  In Python 2.5, it becomes
# email.generator.
import sys, email
from email.Generator import Generator

def prep(nm):
    return nm.strip().lower()

if sys.argv[1] == '-s' or sys.argv[1] == '-d':
    delitems = (sys.argv[1] == '-d')
    emails = {}
    try:
        outfile = open(sys.argv[2], 'r')
        for name in outfile.readlines():
            name = prep(name)
            emails[name] = True
        outfile.close()
    except IOError: pass
    for name in sys.stdin.readlines():
        name = prep(name)
        if delitems:
            if name in emails:
                del emails[name]
                print >> sys.stderr, 'Removing "%s" from whitelist.' % name
        else:
            if not name in emails:
                print >> sys.stderr, 'Adding "%s" to whitelist.' % name
                emails[name] = True
    outfile = open(sys.argv[2], 'w')
    try:
        del emails['niko@alum.mit.edu'] # Hack: keep myself off the whitelist
    except KeyError: pass
    names = emails.keys()
    names.sort()
    for nm in names:
        outfile.write(nm)
        outfile.write('\n')
    outfile.close()
else:
    infile = open (sys.argv[1], 'r')
    emailmsg = email.message_from_file (sys.stdin)
    fromline = prep(emailmsg['From'])
    found = "NO"
    for name in infile:
        name = prep(name)
        if name in fromline:
            found = "YES"
            break
    emailmsg['X-SCF-Whitelist'] = found
    
    g = Generator(sys.stdout, mangle_from_=False, maxheaderlen=60)    
    g.flatten(emailmsg)
