#!/bin/bash
# info: delete remote dns domains
# options: [HOST]
# The function deletes remote dns domains.


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

# Argument definition
host=$1

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


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

is_system_enabled "$DNS_CLUSTER" 'DNS_CLUSTER'
is_procces_running
remote_dns_health_check


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

IFS=$'\n'

if [ -z $host ]; then
    hosts=$(cat $VESTA/conf/dns-cluster.conf)
else
    hosts=$(grep "HOST='$host'" $VESTA/conf/dns-cluster.conf)
fi

# Starting cluster loop
for cluster in $hosts; do

    # Parsing remote host parameters
    eval $cluster

    # Deleting source records
    cluster_cmd v-delete-dns-domains-src $DNS_USER $HOSTNAME 'no'
    check_result $? "$HOST connection failed (cleanup)" $E_CONNECT

    # Rebuilding dns zones
    $send_cmd v-rebuild-dns-domains $DNS_USER 'yes'
    check_result $? "$HOST connection failed (rebuild)" $E_CONNECT

done


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

# Updating pipe
pipe="$VESTA/data/queue/dns-cluster.pipe"
str=$(grep -n "$SCRIPT $1 $2$" $pipe | cut -f1 -d: | head -n1)
if [ ! -z "$str" ]; then
    sed -i "$str d"  $pipe
fi

exit