#!/bin/bash
# info: delte mail account forward
# options: USER DOMAIN ACCOUNT EMAIL
#
# The function add delete email account forward address.


#----------------------------------------------------------#
#                    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
forward=$4

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


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

check_args '4' "$#" 'USER DOMAIN ACCOUNT FORWARD'
validate_format 'user' 'domain' 'account' 'forward'
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"
fwd=$(get_object_value "mail/$domain" 'ACCOUNT' "$account" '$FWD')
if [ -z "$(echo $fwd | grep -w $forward)" ]; then
    echo "Error: forward $forward is not exist"
    log_event "$E_NOTEXIST $EVENT"
    exit $E_NOTEXIST
fi


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

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

sed -i "/^$account@$domain:/ d" $HOMEDIR/$user/conf/mail/$domain/aliases
echo "$account@$domain:$fwd" >> $HOMEDIR/$user/conf/mail/$domain/aliases


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

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

# Logging
log_history "deleted $forward forward on $account@$domain"
log_event "$OK" "$EVENT"

exit
