#!/bin/bash
# info: delete mail account forward
# options: USER DOMAIN ACCOUNT EMAIL
#
# example: v-delete-mail-account-forward admin acme.com tony bob@acme.com
#
# This function deletes an email accounts forwarding address.

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

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

# 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 '4' "$#" 'USER DOMAIN ACCOUNT FORWARD'
is_format_valid 'user' 'domain' 'account'
if [ "$forward" != ':blackhole:' ]; then
	is_format_valid 'forward'
fi
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"
fwd=$(get_object_value "mail/$domain" 'ACCOUNT' "$account" '$FWD')
if [ -z "$(echo $fwd | grep -w $forward)" ]; then
	check_result "$E_NOTEXIST" "forward $forward doesn't exist"
fi

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

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

# Define new fwd string
fwd=$(echo "$fwd" \
	| sed "s/,/\n/g" \
	| sed "s/^$forward$//g" \
	| sed "/^$/d" \
	| sed ':a;N;$!ba;s/\n/,/g')

# Deleting exim forward
if [[ "$MAIL_SYSTEM" =~ exim ]]; then
	sed -i "/^$account@$domain_idn:/ d" $HOMEDIR/$user/conf/mail/$domain/aliases
	echo "$account@$domain_idn:$fwd" >> $HOMEDIR/$user/conf/mail/$domain/aliases
fi

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

# Updating config
update_object_value "mail/$domain" 'ACCOUNT' "$account" '$FWD' "$fwd"

# Logging
$BIN/v-log-action "$user" "Info" "Mail" "Mail account forwarding address removed (User: $account@$domain, Send To: $forward)."
log_event "$OK" "$ARGUMENTS"

exit
