#!/usr/bin/env python
#
# Copyright (C) 2001,2002,2003 Jason R. Mastaler <jason@mastaler.com>
#
# This file is part of TMDA.
#
# TMDA is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.  A copy of this license should
# be included in the file COPYING.
#
# TMDA is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with TMDA; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

"""Generate a tagged e-mail address.

Usage:  %(program)s OPTIONS

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

	-V
	--version
	   Print TMDA version information and exit.

	-c <file>
	--config-file <file>
	   Specify a configuration file other than the default.

	-a <address>
	--address <address>
	   Specify a different address as the basis for the tagged address.
	   
	-n
	--no-newline
	   Do not print a newline after the address.

	-k <keyword>
	--keyword <keyword>
	   Generate a keyword-style tagged address.  keyword is
	   a required keyword string.

	-s <address>
	--sender <address>
	   Generate a sender-style tagged address.  address is
	   a required sender e-mail address or domain name.

	-d [timeout]
	--dated [timeout]
	   Generate a dated-style tagged address.  timeout is an
	   optional timeout interval to override your default.
	   See the output of tmda-pending -h for syntax of timeout.
"""

import getopt
import os
import sys

try:
    import paths
except ImportError:
    # Prepend /usr/lib/python2.x/site-packages/TMDA/pythonlib
    sitedir = os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3],
                           'site-packages', 'TMDA', 'pythonlib')
    sys.path.insert(0, sitedir)

from TMDA import Version

program = sys.argv[0]

def usage(code, msg=''):
    print __doc__ % globals()
    if msg:
        print msg
    sys.exit(code)

def processOpts(args):
    opts = None
    try:
	opts, args = getopt.getopt(args,
                                   'c:a:dk:s:hVn', ['config-file=',
                                                    'address=',
                                                    'dated',
                                                    'keyword=',
                                                    'sender=',
                                                    'help',
                                                    'version',
                                                    'no-newline'])
    except getopt.error, msg:
	usage(1, msg)
    return (opts, args)

opts, args = processOpts(sys.argv[1:])
address = None
tag = 'dated'
option = None
print_newline = 1

for opt, arg in opts[:]:
    if opt in ('-c', '--config-file'):
        os.environ['TMDARC'] = arg
	opts.remove((opt, arg))

from TMDA import Defaults

while len(opts) > 0:
    for opt, arg in opts[:]:
	if opt in ('-h', '--help'):
	    usage(0)
	if opt == '-V':
	    print Version.ALL
	    sys.exit()
	if opt == '--version':
	    print Version.TMDA
	    sys.exit()
	elif opt in ('-a', '--address'):
	    address = arg
	elif opt in ('-d', '--dated'):
	    tag = Defaults.TAGS_DATED[0].lower()
	    option = None
	    try:                        # check for timeout override
		os.environ['TMDA_TIMEOUT'] = args[0]
	    except IndexError:
		pass
	    for tmparg in args[:]:
                if tmparg[0] == '-':
		    break
		args.remove(tmparg)
	    moreOpts, args = processOpts(args)
	    opts.extend(moreOpts)
	elif opt in ('-k', '--keyword'):
	    tag = Defaults.TAGS_KEYWORD[0].lower()
	    option = arg
	elif opt in ('-s', '--sender'):
	    tag = Defaults.TAGS_SENDER[0].lower()
	    option = arg
	elif opt in ('-n', '--no-newline'):
	    print_newline = 0
	opts.remove((opt, arg))


from TMDA import Cookie
from TMDA import Address

def main():
    global address, tag, option, print_newline

    try:
        tagged_address = Address.Factory(tag = tag).create(address, option).address
    except ValueError, msg:
        usage(msg)
        sys.exit(0)

    if not tagged_address:
        usage(0)

    sys.stdout.write(tagged_address)

    if print_newline:
        sys.stdout.write("\n")
    
# This is the end my friend.
if __name__ == '__main__':
    main()
