#!/usr/local/bin/python2.5
'''getmail_maildir
Reads a message from stdin and delivers it to a maildir specified as
a commandline argument.  Expects the envelope sender address to be in the
environment variable SENDER.
Copyright (C) 2001-2008 Charles Cazabon <charlesc-getmail @ pyropus.ca>

This program is free software; you can redistribute it and/or modify it under
the terms of version 2 (only) of the GNU General Public License as published by
the Free Software Foundation.  A copy of this license should be included in the
file COPYING.

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., 59 Temple
Place - Suite 330, Boston, MA  02111-1307, USA.
'''
import sys

if sys.hexversion < 0x2030300:
    raise ImportError('getmail version 4 requires Python version 2.3.3 '
                      'or later')

import os

from getmailcore.message import Message
from getmailcore.utilities import *
from getmailcore.exceptions import *

hostname = localhostname()

verbose = False
path = None
for arg in sys.argv[1:]:
    if arg in ('-h', '--help'):
        sys.stdout.write('Usage: %s maildirpath\n' % sys.argv[0])
        raise SystemExit
    elif arg in ('-v', '--verbose'):
        verbose = True
    elif not path:
        path = arg
    else:
        raise SystemExit('Error: maildir path specified twice (was %s, now %s)'
                         % (path, arg))

if os.name == 'posix' and (os.geteuid() == 0 or os.getegid() == 0):
    raise SystemExit('Error: do not run this program as user root')

if not (path and (path.startswith('.') or path.startswith('/'))
        and path.endswith('/')):
    raise SystemExit('Error: maildir must start with . or / and end with /')

if not is_maildir(path):
    raise SystemExit('Error: %s is not a maildir' % path)

msg = Message(fromfile=sys.stdin)
if os.environ.has_key('SENDER'):
    msg.sender = os.environ['SENDER']
if os.environ.has_key('RECIPIENT'):
    msg.recipient = os.environ['RECIPIENT']

try:
    d = deliver_maildir(path, msg.flatten(True, False), hostname)
except getmailDeliveryError, o:
    raise SystemExit('Error: delivery error delivering to maildir %s (%s)'
                     % (path, o))
except StandardError, o:
    raise SystemExit('Error: other error delivering to maildir %s (%s)'
                     % (path, o))

if verbose:
    sys.stdout.write('Delivered to maildir %s\n' % path)
