#!/bin/bash
#
# ::do_not_edit::
# ::maintainer::
#
CMD=$(basename "$0")
CMDVER="1.1"
CMDSTR="$CMD v$CMDVER (2025-03-15)"

set -e -u



usage()
{
	echo "
== $CMDSTR == add/update virtual dovecot mailuser ==

usage: $CMD username

- password are stored with SHA256 algo
" >&2
	exit 1
}


# (MAIN)

dbfile="/etc/dovecot/users"

[ $# != 1 ] && usage

origuser=$1; shift
pass=
quota="1G"

user=$(echo "$origuser" | tr '[A-Z]' '[a-z]')
[ "X$user" != "X$origuser" ] && {
	echo -e "\n warning: username translated to lowercase: $user"
}


if grep -q "^$user:" $dbfile
then
	echo -e "\n updating existing user: $user in $dbfile\n"
else
	echo -en "\n adding new user: $user to $dbfile\n"
fi

while :
do
	echo -en " quota [$quota]: "
	read ans || exit 1
	ans=${ans:-$quota}
	case $ans in
	 "") continue ;;
	esac
	quota=$ans
	break
done


pass=$(doveadm pw -s sha256-crypt) || exit 1

if grep -q "^$user:" $dbfile
then
	echo -en "\n updating $user: ... "
	grep -v "^$user:" $dbfile >$dbfile.new
else
	echo -en "\n adding $user ... "
	cp -a $dbfile $dbfile.new
fi

echo "$user:$pass\:\:\:\:\:\:userdb_quota_rule=*:storage=$quota" >>$dbfile.new
rm -f $dbfile.old
mv $dbfile $dbfile.old
mv $dbfile.new $dbfile

chown --reference $dbfile.old $dbfile
chmod --reference $dbfile.old $dbfile

echo "OK"
echo

exit 0
