scripts/mail/mailadmin.sh

106 lines
2.6 KiB
Bash
Executable File

#!/bin/bash
#
# Script to add/delete users or change their passwords for
# Dovecot/Postfix using Virtual Users
USAGE="Usage: $0 OPTION EMAIL [BASEDIR]\n\nOptions:\n\t-a: add user\n\t-d: delete user\n\t-c: change password"
if [ ! -n "$2" ]
then
echo -e $USAGE
exit 1
fi
USERNAME=$(echo "$2" | cut -f1 -d@);
DOMAIN=$(echo "$2" | cut -f2 -d@);
MAIL_REGEX="^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$"
if [[ ! "$2" =~ $MAIL_REGEX ]]; then
echo "ERROR: Invalid email address."
exit 2
fi
ADDRESS=$2
if [ -n "$3" ]
then
if [ ! -d "$3" ]; then
echo -e $USAGE
echo "ERROR: BASEDIR must be a valid directory!"
echo "I would have tried $(postconf | grep ^virtual_mailbox_base | cut -f3 -d' ')"
exit 2
else
BASEDIR="$3"
fi
else
BASEDIR="$(postconf | grep ^virtual_mailbox_base | cut -f3 -d' ')"
fi
VMAILBOX="/etc/postfix/vmailbox"
PASSWD="$BASEDIR/$DOMAIN/passwd"
SHADOW="$BASEDIR/$DOMAIN/shadow"
[ -d "$BASEDIR/$DOMAIN" ] || (mkdir "$BASEDIR/$DOMAIN" && chown vmail:vmail "$BASEDIR/$DOMAIN")
[ -f "$VMAILBOX" ] || (touch $VMAILBOX && echo "Warning: $VMAILBOX not existent. Creating it.")
case $(echo $1 | cut -f2 -d-) in
# Add user
'a')
grep_ret=1
paths=("$PASSWD" "$SHADOW")
for p in $paths; do
grep "$USERNAME:" $p > /dev/null 2>&1
grep_ret=$(($grep_ret && $?))
done
grep "$ADDRESS" $VMAILBOX > /dev/null 2>&1
if [ 1 -ne $(($grep_ret && $?)) ]; then
echo "ERROR: User $ADDRESS already exists."
exit 3
fi
if [ -f $VMAILBOX ]
then
echo "Adding Postfix user configuration..."
echo $ADDRESS $DOMAIN/$USERNAME/ >> $VMAILBOX
postmap $VMAILBOX
if [ $? -eq 0 ]
then
echo "Adding Dovecot user configuration..."
echo $USERNAME::5000:5000::$BASEDIR/$DOMAIN/$USERNAME >> $PASSWD
echo $USERNAME":"$(doveadm pw -s SHA512-CRYPT) >> $SHADOW
chown vmail:vmail $PASSWD && chmod 600 $PASSWD
chown vmail:vmail $SHADOW && chmod 600 $SHADOW
/etc/init.d/postfix reload
fi
fi
;;
# Delete user
'd')
echo "Deleting user $ADDRESS. Remove user's mail directory? [y/n]: "
sed -i "/$ADDRESS.*/d" $VMAILBOX
postmap $VMAILBOX
sed -i "/$USERNAME.*/d" $PASSWD
sed -i "/$USERNAME.*/d" $SHADOW
rm -rI "$BASEDIR/$DOMAIN/$USERNAME" > /dev/null 2>&1
if [ ! -s $SHADOW ] && [ ! -s $PASSWD ] && [ $(find $BASEDIR/$DOMAIN -maxdepth 0 -type d 2>/dev/null) ]; then
echo "Remove empty directory $BASEDIR/$DOMAIN? [y/n]: "
rm -rI "$BASEDIR/$DOMAIN" > /dev/null 2>&1
fi
/etc/init.d/postfix reload
;;
# Change user's password
'c')
echo "Changing password for $ADDRESS"
sed -i "s#$USERNAME:.*#$USERNAME:$(doveadm pw -s SHA512-CRYPT)#" $SHADOW
;;
*)
echo -e $USAGE
;;
esac
exit 0