#!/bin/bash
# info: delete mail account
# options: USER DOMAIN ACCOUNT
#
# example: v-delete-mail-account admin acme.com alice
#
# This function deletes email account.

#----------------------------------------------------------#
#                Variables & Functions                     #
#----------------------------------------------------------#

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

# Includes
# shellcheck source=/etc/hestiacp/hestia.conf
source /etc/hestiacp/hestia.conf
# shellcheck source=/usr/local/hestia/func/main.sh
source $HESTIA/func/main.sh
# shellcheck source=/usr/local/hestia/func/domain.sh
source $HESTIA/func/domain.sh
# load config file
source_conf "$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_valid 'mail' 'DOMAIN' "$domain"
is_object_valid "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
	sed -i "/^$account:/d" $HOMEDIR/$user/conf/mail/$domain/accounts
	sed -i "/^$account$/d" $HOMEDIR/$user/conf/mail/$domain/fwd_only
	sed -i "/^$account@$domain_idn:/d" $HOMEDIR/$user/conf/mail/$domain/limits
	rm -rf $HOMEDIR/$user/mail/$domain_idn/$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
$BIN/v-log-action "$user" "Info" "Mail" "Mail account removed (User: $account@$domain)."
log_event "$OK" "$ARGUMENTS"

exit
