#!/bin/bash
# info: list remote dns host
# options: [FORMAT]
#
# example: v-list-remote-dns-hosts json
#
# This function for obtaining the list of remote dns host.

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

# Argument definition
format=${1-shell}

# 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
# load config file
source_conf "$HESTIA/conf/hestia.conf"

# JSON list function
json_list() {
	IFS=$'\n'
	i=1
	objects=$(grep HOST $HESTIA/conf/dns-cluster.conf | wc -l)
	echo "{"
	while read str; do
		parse_object_kv_list "$str"
		echo -n '    "'$HOST'": {
        "PORT": "'$PORT'",
        "TYPE": "'$TYPE'",
        "USER": "'$USER'",
        "DNS_USER": "'$DNS_USER'",
        "SUSPENDED": "'$SUSPENDED'",
        "TIME": "'$TIME'",
        "DATE": "'$DATE'"
    }'
		if [ "$i" -lt "$objects" ]; then
			echo ','
		else
			echo
		fi
		((i++))
	done < <(cat $HESTIA/conf/dns-cluster.conf)
	echo '}'
}

# SHELL list function
shell_list() {
	IFS=$'\n'
	echo "HOST   PORT   TYPE   USER  DNS_USER   SPND   DATE"
	echo "----   ----   ----   ----  --------   ----   ----"
	while read str; do
		parse_object_kv_list "$str"
		echo "$HOST $PORT $TYPE $USER $DNS_USER $SUSPENDED $DATE"
	done < <(cat $HESTIA/conf/dns-cluster.conf)
}

# PLAIN list function
plain_list() {
	IFS=$'\n'
	while read str; do
		parse_object_kv_list "$str"
		echo -ne "$HOST\t$PORT\t$TYPE\t$USER\t$DNS_USER\t"
		echo -e "$SUSPENDED\t$TIME\t$DATE"
	done < <(cat $HESTIA/conf/dns-cluster.conf)
}

# CSV list function
csv_list() {
	IFS=$'\n'
	echo "HOST,PORT,TYPE,USER,DNS_USER,SUSPENDED,TIME,DATE"
	while read str; do
		parse_object_kv_list "$str"
		echo "$HOST,$PORT,$TYPE,$USER,$DNS_USER,$SUSPENDED,$TIME,$DATE"
	done < <(cat $HESTIA/conf/dns-cluster.conf)
}

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

if [ ! -e "$HESTIA/conf/dns-cluster.conf" ]; then
	exit
fi

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

# Listing data
case $format in
	json) json_list ;;
	plain) plain_list ;;
	csv) csv_list ;;
	shell) shell_list | column -t ;;
esac

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

exit
