#! /usr/bin/python
#
# Copyright (C) 2002-2007 by the Free Software Foundation, Inc.
#
# This program 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.
#
# This program 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 this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
# USA.

"""Inject a message from a file into Mailman's incoming queue.

Usage: inject [options] [filename]

Options:

    -h / --help
        Print this text and exit.

    -l listname
    --listname=listname
        The name of the list to inject this message to.  Required.

    -q queuename
    --queue=queuename
        The name of the queue to inject the message to.  The queuename must be
        one of the directories inside the qfiles directory.  If omitted, the
        incoming queue is used.

filename is the name of the plaintext message file to inject.  If omitted,
standard input is used.
"""

import sys
import os
import getopt

import paths
from Mailman import mm_cfg
from Mailman import Utils
from Mailman import Post
from Mailman.i18n import _



def usage(code, msg=''):
    if code:
        fd = sys.stderr
    else:
        fd = sys.stdout
    print >> fd, _(__doc__)
    if msg:
        print >> fd,            if e.errno <> errno.ENOTDIR:
                raise
            print _('Warning!  Not a directory: %(dirpath)s')



# Implementations taken from the pre-2.1.5 Switchboard
def ext_read(filename):
    fp = open(filename)
    d = marshal.load(fp)
    # Update from version 2 files
    if d.get('version', 0) == 2:
        del d['filebase']
    # Do the reverse conversion (repr -> float)
    for attr in ['received_time']:
        try:
            sval = d[attr]
        except KeyError:
            pass
        else:
            # Do a safe eval by setting up a restricted execution
            # environment.  This may not be strictly necessary since we
            # know they are floats, but it can't hurt.
            d[attr] = eval(sval, {'__builtins__': {}})
    fp.close()
    return d


def dequeue(filebase):
    # Calculate the .db and .msg filenames from the given filebase.
    msgfile = os.path.join(filebase + '.msg')
    pckfile = os.path.join(filebase + '.pck')
    dbfile = os.path.join(filebase + '.db')
    # Now we are going to read the message and metadata for the given
   