#!/bin/bash
# info: delete webmail support for a domain
# options: USER DOMAIN [RESTART] [QUIET]
#
# this function removes support for webmail from
# a specified mail domain.

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

# Argument definition
user=$1
domain=$2
restart="$3"
quiet=$4

# Includes
source $HESTIA/func/main.sh
source $HESTIA/func/domain.sh
source $HESTIA/conf/hestia.conf

# Additional argument formatting
format_domain
format_domain_idn

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

check_args '2' "$#" 'USER DOMAIN [RESTART]'
is_format_valid 'user' 'domain'
is_system_enabled "$MAIL_SYSTEM" 'MAIL_SYSTEM'
is_system_enabled "$WEB_SYSTEM" 'WEB_SYSTEM'
is_system_enabled "$IMAP_SYSTEM" 'IMAP_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                             #
#----------------------------------------------------------#

if [ ! -z "$WEBMAIL_ALIAS" ]; then
    # Delete webmail configuration
    del_webmail_config
    del_webmail_ssl_config

    # Ensure that corresponding DNS records are removed
    if [ ! -z "$DNS_SYSTEM" ]; then
        dns_domain=$($BIN/v-list-dns-domains $user | grep $domain | cut -d' ' -f1)
        webmail_record=$($BIN/v-list-dns-records $user $domain | grep -i $WEBMAIL_ALIAS | cut -d' ' -f1)

        if [ "$dns_domain" = "$domain" ]; then
            if [ ! -z "$webmail_record" ]; then
                $BIN/v-delete-dns-record $user $domain $webmail_record
            fi
        fi
    fi
else
    echo "Error: WEBMAIL_ALIAS is not defined in hestia.conf."
fi

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

if [ ! -z "$3" ]; then
    # Restarting web server
    $BIN/v-restart-web $restart
    check_result $? "Web restart failed" >/dev/null

    $BIN/v-restart-proxy $restart
    check_result $? "Proxy restart failed" >/dev/null
fi

# Logging
if [ "$quiet" != 'yes' ]; then
    log_history "disabled webmail support for $domain"
fi
log_event "$OK" "$ARGUMENTS"

exit
