#!/bin/sh
#
# Original author: Matthew Farrellee < mafarrel <at> cs <dot> indiana <dot> edu >
# Date: Monday January 28, 2002
#
# Modified:
# Tuesday January 29, 2002: Made errors more readable.
#
# Modified by Darren Spruell < sancho <at> sancho2k <dot> net >:
# Friday January 10, 2003: Removed the stuff regarding the
# user's domain, etc. My mail host serves a single domain.
# Made some minor editions to the script.
#
# Modified by Daniel Tams < dantams <at> sdf-eu <dot> org >:
# Friday July 04, 2003: Changed binary variables to values that  
# conform to a standard installation of courier-imap on OpenBSD.
# Changed password type to hmac-md5 for CRAM-MD5 secure 
# authentification.

##################################################################
# .: START CONFIGURABLE OPTIONS SECTION :.
##################################################################

# The following paths need to be set to reflect the location of
# the following commands, in order:
# maildirmake, makeuserdb, userdbpw, userdb
MAILDIRMAKE=/var/qmail/bin/maildirmake
MAKEUSERDB=/usr/local/sbin/makeuserdb
USERDBPW=/usr/local/sbin/userdbpw
USERDB=/usr/local/sbin/userdb

# These variables should reflect:
# VUSER -The name of your virtual user account
# VUSER_UID -The UID of your virtual user account
# VUSER_GID -The GID of your virtual user account (should be same as UID)
# VUSER_HOME -This account's home directory
VUSER=vmail
VUSER_UID=`id -u $VUSER`
VUSER_GID=`id -g $VUSER`
VUSER_HOME=~vmail

# Set this to qmail's home (usually /var/qmail):
QMAIL_HOME=/var/qmail

##################################################################
# .: END CONFIGURABLE OPTIONS SECTION :.
##################################################################

NEW_USER=$1

# Make sure the username argument was given.
if [ -z "$NEW_USER" ]
then
echo "Usage:" `basename $0` "<username>"
echo "Ex: `basename $0` bob"
exit 1
fi

# Make sure the user does not already exist.
if [ -d $VUSER_HOME/Maildir-$NEW_USER ]
then
echo "Error: Account" $NEW_USER "already exists."
exit 1
fi

# Create the user's home and mail directory.
echo "Creating a Maildir for" $NEW_USER
$MAILDIRMAKE $VUSER_HOME/Maildir-$NEW_USER
if [ $? != 0 ]; then
echo "Error creating Maildir..."
exit
fi
chown -R $VUSER.$VUSER $VUSER_HOME/Maildir-$NEW_USER

# Add the user to the proper userdb and set the user's password.
echo "Adding" $NEW_USER "to" /etc/userdb
echo "Enter the password for" $NEW_USER
$USERDBPW -hmac-md5 | $USERDB -f /etc/userdb $NEW_USER set uid=$VUSER_UID gid=$VUSER_GID home=$VUSER_HOME mail=$VUSER_HOME/Maildir-$NEW_USER hmac-md5pw

# Make sure the new user is noticed.
$MAKEUSERDB

# Create .qmail files for delivery to Maildir.
echo "vmail-$NEW_USER" > $QMAIL_HOME/alias/.qmail-$NEW_USER
echo "./Maildir-$NEW_USER/" > $VUSER_HOME/.qmail-$NEW_USER
echo "Created .qmail files for Maildir delivery to $NEW_USER."

# Finalize for user.
echo
echo " Done!!! $NEW_USER has been added to Courier-IMAP."
echo
exit 0
