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


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

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

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


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

check_args '2' "$#" 'USER DOMAIN'
is_format_valid 'user' 'domain'
is_system_enabled "$DNS_SYSTEM" 'DNS_SYSTEM'
is_object_valid 'user' 'USER' "$user"
is_object_unsuspended 'user' 'USER' "$user"
is_object_valid 'dns' 'DOMAIN' "$domain"
is_object_unsuspended 'dns' 'DOMAIN' "$domain"

# Perform verification if read-only mode is enabled
check_hestia_demo_mode


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

records=$(wc -l $USER_DATA/dns/$domain.conf | cut -f 1 -d ' ')

# Deleting system configs
if [[ "$DNS_SYSTEM" =~ named|bind ]]; then
    if [ -e '/etc/named.conf' ]; then
        dns_conf='/etc/named.conf'
    else
        dns_conf='/etc/bind/named.conf'
    fi

    sed -i "/\/$user\/conf\/dns\/$domain.db\"/d" $dns_conf
    rm -f $HOMEDIR/$user/conf/dns/$domain.db
fi

# Updating dns-cluster queue
if [ ! -z "$DNS_CLUSTER" ]; then
    cmd="$BIN/v-delete-remote-dns-domain $user $domain"
    echo "$cmd" >> $HESTIA/data/queue/dns-cluster.pipe
fi


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

# Deleting domain
sed -i "/DOMAIN='$domain'/ d" $USER_DATA/dns.conf
rm -f $USER_DATA/dns/$domain.conf

# Decreasing domain value
decrease_user_value "$user" '$U_DNS_DOMAINS'
decrease_user_value "$user" '$U_DNS_RECORDS' "$records"

# Restarting named
$BIN/v-restart-dns $restart
check_result $? "Bind restart failed" >/dev/null

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

exit
