#!/bin/bash
# info: add mail account forward address
# options: USER DOMAIN ACCOUNT FORWARD
#
# example: v-add-mail-account-forward admin acme.com alice bob
#
# This function add new email account.

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

# Argument definition
user=$1
domain=$2
domain_idn=$2
account=$3
email_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 [ "$email_forward" != ':blackhole:' ]; then
	is_format_valid 'email_forward'
fi
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"
fwd=$(get_object_value "mail/$domain" 'ACCOUNT' "$account" '$FWD')
if [ -n "$(echo $fwd | grep -w "$email_forward")" ]; then
	echo "Error: forward $email_forward exists"
	log_event "$E_EXISTS" "$ARGUMENTS"
	exit $E_EXISTS
fi

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

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

# Define fwd string
if [ -z "$fwd" ]; then
	fwd="$email_forward"
else
	fwd="$fwd,$email_forward"
fi

# Adding forward to exim
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" "Warning" "Mail" "Mail forwarding on mail account $account@$domain enabled (send to: $email_forward)."
log_event "$OK" "$ARGUMENTS"

exit
