#!/bin/bash
# info: delete remote dns host
# options: HOST
#
# example: v-delete-remote-dns-host example.org
#
# This function for deleting the remote dns host from hestia configuration.

#----------------------------------------------------------#
#                Variables & Functions                     #
#----------------------------------------------------------#

# Argument definition
host=$1

# Includes
# shellcheck source=/etc/hestiacp/hestia.conf
source /etc/hestiacp/hestia.conf
# shellcheck source=/usr/local/hestia/func/main.sh
source $HESTIA/func/main.sh
# shellcheck source=/usr/local/hestia/func/remote.sh
source $HESTIA/func/remote.sh
# load config file
source_conf "$HESTIA/conf/hestia.conf"

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

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

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

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

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

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

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

	# Delete cron job
	cmd="sudo $BIN/v-update-sys-queue dns-cluster"
	check_cron=$(grep "$cmd" $HESTIA/data/users/admin/cron.conf 2> /dev/null)
	if [ -n "$check_cron" ]; then
		parse_object_kv_list "$check_cron"
		$BIN/v-delete-cron-job admin "$JOB"
	fi
fi

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

# Logging
$BIN/v-log-action "system" "Info" "System" "Removed remote DNS host (Host: $host)."
log_event "$OK" "$ARGUMENTS"

exit