#!/usr/bin/python
'''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-2003 Charles Cazabon <getmail @ discworld.dyndns.org>

This program is free software; you can redistribute it and/or
modify it under the terms of version 2 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
import os
import socket
import string

sys.path.insert(1, '/usr/lib/getmail')
import getmail_utilities

sender = os.environ.get('SENDER', 'unknown')
hostname = string.split(socket.gethostname(), '.')[0]

try:
    maildir = sys.argv[1]
except IndexError:
    sys.stderr.write('Error: no maildir specified\n')
    raise SystemExit(1)
try:
    msg = sys.stdin.read()
    if msg[:12] != 'Return-Path:':
        msg = 'Return-Path: <%s>\n%s' %(sender, msg)
    getmail_utilities.deliver_maildir(maildir, msg, hostname)
except getmail_utilities.getmailDeliveryException, error:
    sys.stderr.write('Error delivering to maildir "%s" (%s)\n' % (maildir, error))
    raise SystemExit(1)
sys.stdout.write('Delivered to maildir "%s"\n' % maildir)
