#!/usr/bin/env python

######################
# Sender (client) mode
######################

"""Tag and send outgoing messages.

Usage:  %(program)s [OPTIONS] [ recip ... ]

OPTIONS:
	-h
	--help
	   Print this help message and exit.

	-c <file>
	--config-file <file>
	   Specify a different configuration file other than ~/.tmdarc.

        -f <sender>
           This option is silently ignored currently.

        -q
        --qfilter
           Return 99 to qfilter so it will not run qmail-queue itself.

        -O <file>
        --filter-outgoing-file <file>
           Full pathname to your outgoing filter file.  Overrides
           FILTER_OUTGOING in ~/.tmdarc.

        -M <recipient>
        --filter-match <recipient>
           Check whether the given e-mail address matches a line in your outgoing
           filter and then exit.  The address given should be that of the message
           recipient.  This option will also check for parsing errors in the
           filter file.
           
	recip
	   If one or more recipients are provided, send the message to
	   all recip arguments.  If none are provided, send the message
	   to all header recipient addresses.
"""

import getopt
import os
import sys

filter_match = None
qfilter = None
program = sys.argv[0]

def usage(code, msg=''):
    print __doc__ % globals()
    if msg:
        print msg
    sys.exit(code)
    
try:
    opts, args = getopt.getopt(sys.argv[1:],
                               'c:O:M:qhf:', ['config-file=',
                                              'filter-outgoing-file=',
                                              'filter-match=',
                                              'qfilter',
                                              'help'])
except getopt.error, msg:
    usage(1, msg)

for opt, arg in opts:
    if opt in ('-h', '--help'):
        usage(0)
    elif opt in ('-M', '--filter-match'):
	filter_match = 1
    elif opt in ('-O', '--filter-outgoing-file'):
	os.environ['TMDA_FILTER_OUTGOING'] = arg
    elif opt in ('-c', '--config-file'):
        os.environ['TMDARC'] = arg
    elif opt in ('-q', '--qfilter'):
        qfilter = 99
    elif opt == '-f':
        pass


try:
    import paths
except ImportError:
    pass

from TMDA import Defaults
from TMDA import Cookie
from TMDA import FilterParser
from TMDA import Util
from TMDA import Version

import popen2
import rfc822
import string


# Just check Defaults.FILTER_OUTGOING for syntax errors and possible
# matches, and then exit.
if filter_match:
    recip = sys.argv[-1]
    Util.filter_match(Defaults.FILTER_OUTGOING, recip)
    sys.exit()

message = sys.stdin
message_headers = rfc822.Message(message)


def message_format(fsa, ffn, type):
    # "angles" is the default MESSAGE_FROM_STYLE
    if type == 'parens':
        return '%s (%s)' % (fsa, ffn)
    elif type == 'address':
        return '%s' % (fsa)
    elif type == 'unquoted':
        return '%s <%s>' % (ffn, fsa)
    else:
        return '"%s" <%s>' % (ffn, fsa)


def make_field(cookie_type, cookie_option, from_address, to_address):
    """
    Create an email address based on a cookie type and one or more addresses.
    """
    if cookie_type == 'default':
	cookie_type = Defaults.ACTION_OUTGOING

    if cookie_type == 'bare':
	# Use an untagged address.
	field = from_address
	# Optionally append the recipient address to a file.
	if (cookie_option and string.lower(cookie_option) == 'append'
	    and Defaults.BARE_APPEND):
	    Util.append_to_file(to_address, Defaults.BARE_APPEND)
    elif cookie_type == 'dated':
	# Send a message with a tagged (dated) address.
	if cookie_option:               # check for timeout override
	    os.environ['TMDA_TIMEOUT'] =  cookie_option
	field = Cookie.make_dated_address(from_address)
    elif cookie_type == 'sender':
	# Send a message with a tagged (sender) address
	sender_cookie_address = cookie_option or to_address
	field = Cookie.make_sender_address (from_address, sender_cookie_address)
    elif cookie_type in ('as','exp','explicit') and cookie_option:
	# Send a message with an explicitly defined address.
	field = cookie_option
    elif cookie_type in ('ext','extension') and cookie_option:
	# Send a message with a tagged (extension added) address.
	(username, hostname) = string.split(from_address,'@')
	field = username + Defaults.RECIPIENT_DELIMITER + \
                cookie_option + '@' + hostname
    elif cookie_type in ('kw','keyword') and cookie_option:
	# Send a message with a tagged (keyword) address.
	field = Cookie.make_keyword_address(from_address, cookie_option)
    else:
	# If cookie_type is invalid, punt and use an untagged address.
	field = from_address
    return field


def inject_message(resending,
                   to_address,
                   from_address,
		   full_name,
                   message_headers,
                   message_body,
                   actions):
    """Hand the message off to sendmail."""
    # Default, if no From: is specified, is bare.
    (cookie_type, cookie_option) = actions.get('from', ('bare', from_address))
    magic_from = make_field(cookie_type, cookie_option,
                            from_address, to_address)
    envelope_sender = resent_from = magic_from
    # Update envelope_sender with user-specified header
    (cookie_type, cookie_option) = actions.get('envelope', (None, None))
    if cookie_type:
	envelope_sender = make_field(cookie_type, cookie_option,
                                     from_address, to_address)
    # Update resent_from with user-specified header
    (cookie_type, cookie_option) = actions.get('resent-from', (None, None))
    if cookie_type:
	resent_from = make_field(cookie_type, cookie_option,
                                 from_address, to_address)
    # Set From: or Resent-From: to match the envelope sender address.
    if resending:
	message_headers['Resent-From'] = message_format(resent_from, full_name,
                                                        Defaults.MESSAGE_FROM_STYLE)
    else:
	message_headers['From'] = message_format(magic_from, full_name,
                                                 Defaults.MESSAGE_FROM_STYLE)
    # Add in any custom headers
    for header in actions.keys():
	if header in ('from', 'envelope', 'resent-from'):
	    continue
	(cookie_type, cookie_option) = actions[header]
	field = make_field(cookie_type, cookie_option, from_address, to_address)
	nice_header = string.replace(string.capwords(
            string.replace(header, '-', ' ')), ' ', '-')
        message_headers[nice_header] = message_format(field, full_name,
                                                      Defaults.MESSAGE_FROM_STYLE)
    # If the MUA has added a `Mail-Followup-To' header that contains
    # the untagged address, we need to tag that as well.
    if message_headers.has_key('mail-followup-to'):
	mft_list = message_headers.getaddrlist('mail-followup-to')
	new_mft_list = []
	for a in mft_list:
	    emaddy = a[1]
	    if emaddy == from_address:
		new_mft_list.append(magic_from)
	    else:
		new_mft_list.append(emaddy)
	message_headers['Mail-Followup-To'] = string.join(new_mft_list, ',\n\t')
    # Add `Date' and `Message-ID' headers only if they don't already exist.
    if not message_headers.has_key('date'):
	message_headers['Date'] = Util.make_date()
    if not message_headers.has_key('message-id'):
	message_headers['Message-ID'] = Util.make_msgid()
    # Add `X-Delivery-Agent' header.
    message_headers['X-Delivery-Agent'] = Version.ALL
    # Optionally, add an `X-TMDA-Fingerprint' header.
    if Defaults.FINGERPRINT:
	hdrlist = []
	for hdr in Defaults.FINGERPRINT:
	    hdrval = message_headers.getheader(hdr, None)
	    if hdrval:
		hdrlist.append(hdrval)
	if hdrlist:
	    message_headers['X-TMDA-Fingerprint'] = (
		Cookie.make_fingerprint(hdrlist))
    # Optionally, remove some headers.
    if Defaults.PURGED_HEADERS:
	for hdr in Defaults.PURGED_HEADERS:
	    del message_headers[hdr]
    # Inject the message.
    inject = []
    inject.append(Defaults.SENDMAIL)
    inject.append('-f')
    inject.append(envelope_sender)
    inject.append(to_address)
    pipeline = popen2.popen2(inject)[1]
    pipeline.write(str(message_headers))
    pipeline.write('\n')
    pipeline.write(message_body)
    pipeline.close()


######
# Main
######

def main():

    x_tmda_over = None
    actions = None

    if message_headers.has_key('resent-from'):
        # We must be resending (bouncing) the message.
        (fullname, from_address) = message_headers.getaddr('resent-from')
        resending = 1
    else:
        # Use the existing From: header if possible.
        (fullname, from_address) = message_headers.getaddr("from")
        resending = None
    if not fullname:
        fullname = Defaults.FULLNAME
    if not from_address or len(string.split(from_address,'@')) != 2:
        from_address = Defaults.USERNAME + '@' + Defaults.HOSTNAME
    
    # Read in the message body.
    message_body = message.read()
    
    # If recipients were provided as arguments, use them.
    if args:
        address_list = args
    # If running through qfilter, get recipient list from QMAILRCPTS.
    elif os.environ.has_key('QMAILRCPTS'):
        address_list = string.split(string.lower
                                    (os.environ['QMAILRCPTS']),'\n')[:-1]
    # Otherwise get recipients from the headers.
    else:
        address_list = []
        if resending:
            # Use Resent-To, Resent-Cc, and Resent-Bcc addresses.
            header_pairs = message_headers.getaddrlist('resent-to') + \
                           message_headers.getaddrlist('resent-cc') + \
                           message_headers.getaddrlist('resent-bcc')
        else:
            # Use To, Cc, Bcc, and Apparently-To addresses.
            header_pairs = message_headers.getaddrlist('to') + \
                           message_headers.getaddrlist('cc') + \
                           message_headers.getaddrlist('bcc') + \
                           message_headers.getaddrlist('apparently-to')
        for pair in header_pairs:
            address = pair[1]
            address_list.append(address)

    # Check for the `X-TMDA' override header.
    if message_headers.has_key('x-tmda'):
        x_tmda_over = 1
        x_tmda = message_headers.getheader('x-tmda')
        # X-TMDA should only have one field.
        if len(string.split(x_tmda)) == 1:
	    actions = { 'from' : FilterParser.splitaction(x_tmda) }
        # Delete `X-TMDA' before sending.
        del message_headers['x-tmda']
    else:
        # Without `X-TMDA', we need to parse the outgoing filter file.
        outfilter = FilterParser.FilterParser()
        outfilter.read(Defaults.FILTER_OUTGOING)

    # If the address matches a line in the filter file, it is tagged
    # accordingly, otherwise it is tagged with the default cookie
    # type.
    for address in address_list:
        # If `X-TMDA' is present we are done here.
        if x_tmda_over:
            pass                        
        else:
            (actions, matching_line) = outfilter.firstmatch(address)
        if not actions:
	    actions = { 'from' : (string.lower(Defaults.ACTION_OUTGOING), None) }
        # The message is sent to each recipient separately so that
        # everyone gets the correct tag.  Make sure your MUA
        # generates its own Message-ID: and Date: headers so they
        # match on multiple recipient messages.
        inject_message(resending,
                       address,
                       from_address,
		       fullname,
                       message_headers,
                       message_body,
                       actions)
    if qfilter:
        sys.exit(qfilter)
    else:
        sys.exit(Defaults.EX_OK)


# This is the end my friend.
if __name__ == '__main__':
    main()
