#!/bin/bash

#
# courier-vmailsetup.sh  
#
# (c) 2003 Dave Kliczbor (maligree@gmx.de)
# Version 0.1 (2004-01-09)
#
# Sets up virtual domains/users for courier according to
# http://da.andaka.org/Doku/courier-vmaildir.html
#
# If you want to use the default config settings,
# just make a touch /etc/courier/vmail/config
# If not, edit that file. You may enter the variables
# introduced below.
#

PATH=/usr/sbin:/usr/bin:/bin:/usr/local/bin

VMAILNAME="vmail"
VMAILUSER="mail"
VMAILDIR="/var/mail"
COURIERCONFIGDIR="/etc/courier"
DOMAINCONFIG="$COURIERCONFIGDIR/$VMAILNAME/config"
DOMAINPATHPREFIX="domains"
MAILDIRSKEL="$COURIERCONFIGDIR/$VMAILNAME/skel"

if [ `whoami` != "root" ]
then
        echo "Error: whoami said you're not root. You're `whoami`"
        exit 1
fi

if [ -r $DOMAINCONFIG ]
then
        source $DOMAINCONFIG
else
        echo "Error: $DOMAINCONFIG not found."
	echo "If you want to use the default file paths, run"
	echo " # touch $DOMAINCONFIG"
	echo "If you want to use other paths, just insert the config variables"
	echo "as used in $0."
	echo "Nevertheless, you are stuck with /etc/courier/vmail/config"
	echo "as config file unless you edit $0."
        exit 2
fi

if [ -f "$COURIERCONFIGDIR/userdb" ]
then
	echo "Warning: $COURIERCONFIGDIR/userdb already exists and is a file\!"
	echo "I'll create a directory and move the file into it."
	mv "$COURIERCONFIGDIR/userdb" "$COURIERCONFIGDIR/userdb.tmp"
	mkdir -p "$COURIERCONFIGDIR/userdb"
	mv "$COURIERCONFIGDIR/userdb.tmp" "$COURIERCONFIGDIR/userdb/userdb"
else	
	echo "Creating $COURIERCONFIGDIR/userdb"
	mkdir -p "$COURIERCONFIGDIR/userdb"
fi

chmod 700 "$COURIERCONFIGDIR/userdb"

echo "Adding system user $VMAILUSER to userdb and refreshing it"
pw2userdb |grep -e "\<$VMAILUSER\>" >"$COURIERCONFIGDIR/userdb/$VMAILNAME"
makeuserdb

