# AutoApprove v 0.2
# by whatah

import os

"""Automatically approve certain addresses and change the from field."""


APPROVED_LIST = "/etc/mailman/approved.list"
# the approved list is in the format:
# list.to.approve.for:address.it.is.coming@from:The Name <address.to.replace.it@with>
# list.to.approve.for:address.it.is.coming@from:address.to.replace.it@with
# lines beginning with a # or blank lines are comments
def sepatcolon(message):
    split_index = message.find(':')
    ret = []
    ret.append(message[:split_index])
    ret.append(message[split_index+1:])
    return ret

# Returns a dictionary of approved addresses and their key values
def getapproved(path_to_approved_file):
    if os.path.exists(path_to_approved_file):
        approved_file = open(path_to_approved_file, 'r')
        approved_lines = approved_file.readlines()
	a_list = {}
        for line in approved_lines:
	    line = line.strip()
            if line == '' or (len(line) > 0 and line[0] == '#'):
	    	continue
	    split_line = sepatcolon(line)
	    a_listname = split_line[0]
	    split_line = sepatcolon(split_line[1])
	    a_address = split_line[0].lower()
	    r_address = split_line[1]
	    a_list[(a_listname, a_address)] = r_address
        return a_list
    else:
        # Log that the file doesn't exist
        pass
    return {}

def process(mlist, msg, msgdata):
    approved_addresses = getapproved(APPROVED_LIST)
    # Not sure if i should be using msg['from'] or msg.get_sender() here
#    sender = msgdata.get('sender', msg.get_sender()).lower()
    sender = msg.get_sender()).lower()
    listname = mlist.internal_name().lower()
    if approved_addresses.has_key((listname, sender)):
    	_from = approved_addresses[(listname, sender)].rstrip()
        _header = msgdata['header'].replace(sender, _from)
        msgdata['approved'] = 1
        # Log that we approved the message here
        pass
        #Debugging statement
        # Now change the from header
	try:
	    msg.replace_header('from', _from)
            msg.replace_header('header', _header)
	except:
	    pass
        #Debugging statement
        return
    # Log that we got an unapproved message
    pass
    # We let the mail go through, so it hits the moderation queue otherwise
