#!/bin/sh
#
# mailman.sh by Davide Libenzi (Integration script for XMail and Mailman)
# Copyright (C) 2008  Davide Libenzi
#
# 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# Davide Libenzi <davidel@xmailserver.org>
#
#
# This script takes an incoming list for a mailing list and parses
# the email address to determine the correct list for sending to
# Mailman's wrapper program

usage()
{
    printf "Use: %s RCPT FILE\n" $(basename $1) >&2
    exit 1
}


if [ "$MAIL_ROOT" == "" ]; then
    MAIL_ROOT=/home/xmailuser/MailRoot
fi

if [ "$MAILMAN_ROOT" == "" ]; then
    MAILMAN_ROOT=/home/mailman/build
fi

if [ "$LOGFILE" == "" ]; then
    LOGFILE=/dev/null
fi

#
# Good for my setup, change in yours
#
MAILMAN_USER=mailman

while getopts 'u:g:l:X:M:U:' OPTION
do
    case $OPTION in
	u)
	    MMUID="$OPTARG"
	    ;;
	g)
	    MMGID="$OPTARG"
	    ;;
	l)
	    LOGFILE="$OPTARG"
	    ;;
	X)
	    MAIL_ROOT="$OPTARG"
	    ;;
	M)
	    MAILMAN_ROOT="$OPTARG"
	    ;;
	U)
	    MAILMAN_USER="$OPTARG"
	    ;;
	?)
	    usage $0
	    ;;
    esac
done
shift $(($OPTIND - 1))

if [ $# -lt 2 ]; then
    usage $0
fi

MMUID=`id -u $MAILMAN_USER`
MMGID=`id -g $MAILMAN_USER`

#
# http://www.xmailserver.org/econv.c
# http://www.xmailserver.org/swrap.c
#
ECONV="$MAIL_ROOT/bin/econv"
SWRAP="$MAIL_ROOT/bin/swrap"

# Arguments
LIST_EMAIL=$1
MSGFILE=$2

# First, isolate the list address (i.e. list-owner, list-subscribe, etc.)
LIST_ADDRESS=`echo "$LIST_EMAIL" | sed 's/@.*//g'`

# Next, isolate the list name
LIST_NAME=`echo "$LIST_ADDRESS" | sed 's/\(.*\)-[^-]$/\1/g'`

# Isolate the list user (i.e. owner, admin, subscribe, etc.)
LIST_USER=`echo "$LIST_ADDRESS" | sed 's/.*-\([^-]\)$/\1/g'`

# If the list user is the same as the list name, this means this is
# the address for the list itself, so the list user should be set to post
if [ $LIST_NAME == $LIST_USER ]; then
    LIST_USER=post
fi

# Pipe the email file through ECONV and then to the Mailman
# wrapper for the correct list and user
"$ECONV" --unix --input "$MSGFILE" | "$SWRAP" $MMUID $MMGID "$MAILMAN_ROOT/mail/mailman" \
    $LIST_USER $LIST_NAME >& "$LOGFILE"

