#!/bin/bash
# info: delete mail account
# options: user domain account
#
# The function deletes 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=$3

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


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

check_args '3' "$#" 'user domain account'
validate_format 'user' 'domain' 'account'
is_system_enabled "$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_object_valid "mail/$domain" 'ACCOUNT' "$account"
is_object_unsuspended "mail/$domain" 'ACCOUNT' "$account"


#----------------------------------------------------------#
#                       Action                             #
#----------------------------------------------------------#
aliases=$(get_object_value "mail/$domain" 'ACCOUNT' "$account" '$ALIAS')
for al in ${aliases//,/ }; do
    sed -i "/^$al@$domain:$account/d" $HOMEDIR/$user/conf/mail/$domain/aliases
done

sed -i "/^$account@$domain:/d" $HOMEDIR/$user/conf/mail/$domain/aliases
sed -i "/^$account:/d" $HOMEDIR/$user/conf/mail/$domain/passwd
rm -rf $HOMEDIR/$user/mail/$domain/$account


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

# Update config
sed -i "/ACCOUNT='$account'/d" $USER_DATA/mail/$domain.conf

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


# Logging
log_history "$EVENT"
log_event "$OK" "$EVENT"

exit
