#!/bin/bash
# info: delete mail account
# options: USER DOMAIN ACCOUNT
#
# The function deletes email account.


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

# Argument definition
user=$1
domain=$2
domain_idn=$2
account=$3

# Includes
source $HESTIA/func/main.sh
source $HESTIA/func/domain.sh
source $HESTIA/conf/hestia.conf

# Additional argument formatting
format_domain
format_domain_idn


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

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

# Perform verification if read-only mode is enabled
check_hestia_demo_mode


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

if [[ "$MAIL_SYSTEM" =~ exim ]]; then
    aliases=$(get_object_value "mail/$domain" 'ACCOUNT' "$account" '$ALIAS')
    for al in ${aliases//,/ }; do
        sed -i "/^$al@$domain_idn:$account/d" \
            $HOMEDIR/$user/conf/mail/$domain/aliases
    done

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


#----------------------------------------------------------#
#                       Hestia                             #
#----------------------------------------------------------#

# 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 "deleted $account@$domain mail account"
log_event "$OK" "$ARGUMENTS"

exit
