#!/usr/pkg/bin/python2.7
#
# Copyright (C) 2001-2007 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


from optparse import OptionParser, make_option

import os
import sys
import string
import time

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


# option parsing

opt_usage = "%prog [options] ADDRESS [SENDER]"

opt_desc = \
"""Check a tagged (dated, keyword, or sender style only) e-mail
address.  Required 'ADDRESS' is the address you want to check. Optional
'SENDER' is the sender address to verify if checking a sender-style
address."""

opt_list = [
    make_option("-c", "--config-file",
                metavar="FILE", dest="config_file",
                help=("""Specify a different configuration file other than 
                         ~/.tmda/config""")),
    make_option("-l", "--localtime",
                action="store_true", default=False, dest="localtime",
                help="Display dates in the local time zone instead of UTC"),
    make_option("-V", 
                action="store_true", default=False, dest="full_version",
                help="show full TMDA version information and exit"),
    ]

parser = OptionParser(option_list=opt_list, version=Version.TMDA, 
                      usage=opt_usage, description=opt_desc)
(opts, args) = parser.parse_args()

if opts.full_version:
    print Version.ALL
    sys.exit()
if opts.config_file:
     os.environ['TMDARC'] = opts.config_file
if len(args) < 1:
    parser.error('ADDRESS to check is required.')


from TMDA import Defaults
from TMDA import Address


def formattime(timestamp):
    if opts.localtime:
        timetuple = time.localtime(int(timestamp))
        tzstr = ' %Z'
    else:
        timetuple = time.gmtime(int(timestamp))
        tzstr = ' UTC'
    return time.strftime('%c' + tzstr, timetuple)

def main():
    # Address to check is required
    try:
        address = args[0]
        addr = Address.Factory(address)
    except (IndexError, ValueError):
        parser.error('invalid usage')

    try:
        sender_address = args[1]
    except IndexError:
        sender_address = None

    try:
        addr.verify(sender_address)
        print "STATUS: VALID"
        if addr.tag() in Defaults.TAGS_DATED:
            print "EXPIRES: %s" % formattime(addr.timestamp())
    except Address.ExpiredAddressError, msg:
        print "STATUS:", msg
        print "EXPIRED: %s" % formattime(addr.timestamp())
    except Address.AddressError, msg:
        print "STATUS:", msg


if __name__ == '__main__':
    main()

