#!/bin/bash
# info: list dns domain records
# options: USER DOMAIN [FORMAT]
#
# The function for getting all DNS domain records.


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

# Argument defenition
user=$1
domain=$2
format=${3-shell}

# Includes
source $VESTA/func/main.sh

# Json func
json_list_dns() {
    echo '{'
    fileds_count=$(echo $fields| wc -w )
    while read line; do
        IFS=$'\n'
        eval $line
        if [ -n "$data" ]; then
            echo -e '        },'
        fi
        i=1
        IFS=' '
        for field in $fields; do
            eval value=\"$field\"
            value=$(echo "$value" | sed -e 's/"/\\"/g' -e "s/%quote%/'/g")
            if [ $i -eq 1 ]; then
                (( ++i))
                echo -e "\t\"$value\": {"
            else
                if [ $i -lt $fileds_count ]; then
                    (( ++i))
                    echo -e "\t\t\"${field//$/}\": \"${value//,/, }\","
                else
                    echo -e "\t\t\"${field//$/}\": \"${value//,/, }\""
                    data=1
                fi
            fi
        done
    done < $conf
    if [ -n "$data" ]; then
        echo -e '        }'
    fi
    echo -e '}'
}

# Shell function
shell_list_dns() {

    if [ -z "$nohead" ] ; then
        echo "${fields//$/}"
        for a in $fields; do
            echo -e "------ \c"
        done
        echo
    fi
    while read line ; do
        IFS=$'\n'
        eval $line
        eval echo "$fields" | sed "s/%quote%/'/g"
    done < $conf
}


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

check_args '2' "$#" 'USER DOMAIN [FORMAT]'
validate_format 'user' 'domain'
is_object_valid 'user' 'USER' "$user"
is_object_valid 'dns' 'DOMAIN' "$domain"


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

# Defining config and fields
conf=$USER_DATA/dns/$domain.conf
fields='$ID $RECORD $TYPE $PRIORITY $VALUE $ID $SUSPENDED $TIME $DATE'

# Listing domains
case $format in 
    json)   json_list_dns ;;
    plain)  nohead=1; shell_list_dns ;;
    shell)  fields='$ID $RECORD $TYPE $VALUE';
            shell_list_dns | column -t ;;
    *)      check_args '2' '0' 'USER DOMAIN [FORMAT]'
esac


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

exit
