#!/bin/bash
#
# This script creates a new mailinglist in a Postfix and virtual host
# environment. This scripts updates Postfix config
# ("/etc/postfix/virtual") and aliases table ("/etc/mail/aliases") as
# well as setting up the list with meaningfull "Reply-To" fields, a
# "[listname]" subject prefix, etc.
# 
# 2006 Martin Leopold <leopold@diku.dk>
#

USAGE="new-maillist.sh -D <domain> -L <list-name>"

while getopts ":hD:L:" Option
do
case "$Option" in 
	h )
	echo -e "$USAGE"
	exit 0
	;;
	L )
	LISTNAME="$OPTARG"
	;;
	D )
	FQDN="$OPTARG"
	;;
esac
done

if [ -z "$LISTNAME" ]; then
     echo -e "$USAGE"
     exit 0
fi

if [ -z "$FQDN" ]; then
     echo -e "$USAGE"
     exit 0
fi

echo "Create the mailinglist $LISTNAME@$FQDN [y/N]?"
read OKIDOKI
if [ x"$OKIDOKI" != x"y" ]; then
   exit 0;
fi

# Create a list combining name and domain to allow virtual hosts
SPOOLDIR="/var/spool/mlmmj"
LISTDIR="$SPOOLDIR/$LISTNAME-$FQDN"
./my-mlmmj-make-ml.sh -s $SPOOLDIR -L "$LISTNAME-$FQDN" -D $FQDN

# For some reason this doesn't seem to happen automatically!?
echo "Copying standard mails"
cp /usr/share/mlmmj/text.skel/* $LISTDIR/text

echo "Correcting list address (to $LISTNAME@$FQDN)"
echo "$LISTNAME@$FQDN" >$LISTDIR/control/listaddress

echo "Adding List-Id and Reply-To headers"
echo "List-Id: $LISTNAME.$FQDN" > $LISTDIR/control/customheaders
echo "Reply-To: $LISTNAME@$FQDN" >> $LISTDIR/control/customheaders

echo "Adding a footer to list-posts"
echo "_______________________________________________" >  $LISTDIR/control/footer
# Capitalize first letter
echo -n "${LISTNAME:0:1}" | tr "[:lower:]" "[:upper:]" >> $LISTDIR/control/footer
echo -n "${B}${LISTNAME:1} " >> $LISTDIR/control/footer
echo "mailing list" >> $LISTDIR/control/footer
echo "To unsubscribe send a mail to $LISTNAME+unsubscribe@$FQDN" >> $LISTDIR/control/footer

echo "Adding a subject prefix"
echo "[$LISTNAME]" >  $LISTDIR/control/prefix

echo "Setting list as subscriber post only"
touch $LISTDIR/control/subonlypost

echo "Adding list-redirect to /etc/postfix/virtual"
echo "$LISTNAME@$FQDN	   $LISTNAME-$FQDN" >> /etc/postfix/virtual

echo "Adding list-delivery to /etc/mail/aliases"
echo "$LISTNAME-$FQDN:     \"|/usr/bin/mlmmj-recieve -L $LISTDIR\"" >> /etc/mail/aliases

# Crontab loads its config automatically
echo "Adding list-maintenance to /etc/crontab"
echo "0 */2 * * *  root  /usr/bin/mlmmj-maintd -F -L $LISTDIR" >> /etc/crontab

echo "Chown new mailinglist"
chown -R nobody:apache $LISTDIR
chmod g+r $LISTDIR/archive
chmod g+s $LISTDIR/archive

echo "Rehashing postfix configuration & reloading postfix"
postmap hash:/etc/postfix/virtual
newaliases
/etc/init.d/postfix reload

echo "If this is a new domain don't forget to add the following line to /etc/postfix/virtual"
echo "$LISTNAME@$FQDN                value-required-but-not-used"
echo ""
echo "Don't forget to subscribe someone!"
echo "/usr/bin/mlmmj-sub -L $LISTDIR -a joe@domain.tld"

