#!/bin/bash
# info: list dns domains
# options: USER [FORMAT]
#
# example: v-list-dns-domains admin
#
# This function for obtaining all DNS domains of a user.

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

# Argument definition
user=$1
format=${2-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 DOMAIN $USER_DATA/dns.conf | wc -l)
	echo "{"
	while read str; do
		parse_object_kv_list "$str"
		echo -n '    "'$DOMAIN'": {
        "IP": "'$IP'",
        "TPL": "'$TPL'",
        "TTL": "'$TTL'",
        "EXP": "'$EXP'",
        "SOA": "'$SOA'",
        "SERIAL": "'$SERIAL'",
        "DNSSEC": "'$DNSSEC'",
        "SRC": "'$SRC'",
        "RECORDS": "'$RECORDS'",
        "SUSPENDED": "'$SUSPENDED'",
        "TIME": "'$TIME'",
        "DATE": "'$DATE'"
    }'
		if [ "$i" -lt "$objects" ]; then
			echo ','
		else
			echo
		fi
		((i++))
	done < <(cat $USER_DATA/dns.conf)
	echo '}'
}

# SHELL list function
shell_list() {
	IFS=$'\n'
	echo "DOMAIN   IP   TPL   TTL   DNSSEC   REC   SPND   DATE"
	echo "------   --   ---   ---   ------   ---   ----   ----"
	while read str; do
		parse_object_kv_list "$str"
		echo "$DOMAIN $IP $TPL $TTL $DNSSEC $RECORDS $SUSPENDED $DATE"
	done < <(cat $USER_DATA/dns.conf)
}

# PLAIN list function
plain_list() {
	IFS=$'\n'
	while read str; do
		parse_object_kv_list "$str"
		echo -ne "$DOMAIN\t$IP\t$TPL\t$TTL\t$EXP\t$SOA\t$DNSSEC\t$SERIAL\t"
		echo -e "$SRC\t$RECORDS\t$SUSPENDED\t$TIME\t$DATE"
	done < <(cat $USER_DATA/dns.conf)
}

# CSV list function
csv_list() {
	IFS=$'\n'
	echo "DOMAIN,IP,TPL,TTL,EXP,SOA,SERIAL,SRC,DNSSEC,RECORDS,SUSPENDED,TIME,DATE"
	while read str; do
		parse_object_kv_list "$str"
		echo -n "$DOMAIN,$IP,$TPL,$TTL,$EXP,$SOA,$SERIAL,"
		echo "$SRC,$DNSSEC,$RECORDS,$SUSPENDED,$TIME,$DATE"
	done < <(cat $USER_DATA/dns.conf)
}

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

check_args '1' "$#" 'USER [FORMAT]'
is_format_valid 'user'
is_object_valid 'user' 'USER' "$user"

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

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

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

exit
