#!/bin/bash
# info: add mail domain account
# options: USER DOMAIN ACCOUNT PASSWORD [QUOTA]
#
# The function add new email account.


#----------------------------------------------------------#
#                    Variable&Function                     #
#----------------------------------------------------------#

# Argument defenition
user=$1
domain=$(idn -t --quiet -u "$2" )
domain=$(echo $domain | tr '[:upper:]' '[:lower:]')
domain_idn=$(idn -t --quiet -a "$domain")
account=$(echo $3 | tr '[:upper:]' '[:lower:]')
password=$4
quota=${5-0}

# Includes
source $VESTA/func/main.sh
source $VESTA/func/domain.sh
source $VESTA/conf/vesta.conf

# Hiding password
A4='******'
EVENT="$DATE $TIME $SCRIPT $A1 $A2 $A3 $A4 $A5 $A6 $A7 $A8 $A9"


#----------------------------------------------------------#
#                    Verifications                         #
#----------------------------------------------------------#

check_args '4' "$#" 'USER DOMAIN ACCOUNT PASSWORD [QUOTA]'
validate_format 'user' 'domain' 'account' 'password' 'quota'
is_system_enabled "$MAIL_SYSTEM" 'MAIL_SYSTEM'
is_object_valid 'user' 'USER' "$user"
is_object_unsuspended 'user' 'USER' "$user"
is_object_valid 'mail' 'DOMAIN' "$domain"
is_object_unsuspended 'mail' 'DOMAIN' "$domain"
is_package_full 'MAIL_ACCOUNTS'
is_mail_new "$account"


#----------------------------------------------------------#
#                       Action                             #
#----------------------------------------------------------#

if [ -x '/usr/bin/doveadm' ]; then
    md5=$(/usr/bin/doveadm pw -s md5 -p "$password")
else
    md5=$(/usr/sbin/dovecotpw -s md5 -p "$password")
fi

if [[ "$MAIL_SYSTEM" =~ exim ]]; then
    str="$account:$md5:$user:mail::$HOMEDIR/$user:$quota"
    echo $str >> $HOMEDIR/$user/conf/mail/$domain/passwd
fi


#----------------------------------------------------------#
#                       Vesta                              #
#----------------------------------------------------------#

str="ACCOUNT='$account' ALIAS='' QUOTA='$quota' AUTOREPLY='no' FWD=''"
str="$str FWD_ONLY='' MD5='$md5' U_DISK='0' SUSPENDED='no' TIME='$TIME'"
str="$str DATE='$DATE'"
echo "$str" >> $USER_DATA/mail/$domain.conf
chmod 660 $USER_DATA/mail/$domain.conf

# Increase mail accounts counter
accounts=$(wc -l $USER_DATA/mail/$domain.conf | cut -f 1 -d ' ')
increase_user_value "$user" '$U_MAIL_ACCOUNTS'
update_object_value 'mail' 'DOMAIN' "$domain" '$ACCOUNTS' "$accounts"

# Logging
log_history "added mail account $account@$domain"
log_event "$OK" "$EVENT"

exit
