#!/bin/bash
# info: list remote dns host
# options: [FORMAT]
#
# The function for obtaining the list of remote dns host.


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

# Argument definition
format=${1-shell}

# Includes
source $HESTIA/func/main.sh

# 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
