#!/bin/bash
# info: delete remote dns host
# options: HOST
#
# The function for deleting the remote dns host from vesta configuration.


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

# Argument defenition
host=$1

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


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

check_args '1' "$#" 'HOST'
validate_format 'host'
is_system_enabled "$DNS_CLUSTER" 'DNS_CLUSTER'
is_object_valid "../../conf/dns-cluster" 'HOST' "$host"


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

# Deleting domains
$BIN/v-delete-remote-dns-domains $host >>/dev/null 2>&1

# Disabling restart queue
eval $(grep $host $VESTA/conf/dns-cluster)
case $TYPE in
    ssh) send_cmd="send_ssh_cmd" ;;
    *)  send_cmd="send_api_cmd" ;;
esac
$send_cmd v-add-cron-restart-job

# Deleting server
sed -i "/HOST='$host' /d" $VESTA/conf/dns-cluster.conf

# Delete DNS_CLUSTER key
check_cluster=$(grep HOST $VESTA/conf/dns-cluster.conf |wc -l)
if [ "$check_cluster" -eq '0' ]; then
    rm -f $VESTA/conf/dns-cluster.conf
    sed -i "/DNS_CLUSTER=/d" $VESTA/conf/vesta.conf

    # Delete cron job
    cmd="sudo /usr/local/vesta/bin/v-update-sys-queue dns-cluster"
    check_cron=$(grep "$cmd" $VESTA/data/users/admin/cron.conf 2> /dev/null)
    if [ ! -z "$check_cron" ]; then
        eval $check_cron
        $BIN/v-delete-cron-job admin "$JOB"
    fi
fi


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

# Logging
log_history "deleted $type database server $host" '' 'admin'
log_event "$OK" "$EVENT"

exit
