#!/bin/bash
# info: delete mail domain
# options: USER DOMAIN
#
# The function for deleting MAIL domain. By deleting it all accounts will
# also be deleted.


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

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

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

# Additional argument formatting
format_domain
format_domain_idn


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

check_args '2' "$#" 'USER DOMAIN'
is_format_valid 'user' 'domain'
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"


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

# Get domain values
get_domain_values 'mail'
accounts=$(wc -l $USER_DATA/mail/$domain.conf|cut -f 1 -d ' ')

# Deleting exim configuration files
if [[ "$MAIL_SYSTEM" =~ exim ]]; then
    rm -f /etc/$MAIL_SYSTEM/domains/$domain_idn
    rm -rf $HOMEDIR/$user/conf/mail/$domain
    rm -rf $HOMEDIR/$user/mail/$domain_idn
fi

# Deleting dkim dns record
if [ "$DKIM" = 'yes' ] && [ -e "$USER_DATA/dns/$domain.conf" ]; then
    records=$($BIN/v-list-dns-records $user $domain plain)
    dkim_records=$(echo "$records" |grep -w '_domainkey' | cut -f 1 -d ' ')
    for id in $dkim_records; do
        $BIN/v-delete-dns-record $user $domain $id
    done
fi


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

# Delete domain config
sed -i "/DOMAIN='$domain'/ d" $USER_DATA/mail.conf
rm -f $USER_DATA/mail/$domain.conf
rm -f $USER_DATA/mail/$domain.pem
rm -f $USER_DATA/mail/$domain.pub
rm -f $USER_DATA/mail/*@$domain.msg

# Decreasing domain value
decrease_user_value "$user" '$U_MAIL_DOMAINS'
if [ "$DKIM" = 'yes' ]; then
    decrease_user_value "$user" '$U_MAIL_DKMI'
fi
decrease_user_value "$user" '$U_MAIL_ACCOUNTS' "$accounts"

# Logging
log_history "deleted mail domain $domain"
log_event "$OK" "$ARGUMENTS"

exit
