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


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

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

# Includes
source $VESTA/func/main.sh

# JSON list function
json_list() {
    IFS=$'\n'
    i=1
    objects=$(grep ID $USER_DATA/dns/$domain.conf |wc -l)
    echo "{"
    while read str; do
        eval $str
        VALUE=$(echo "$VALUE" |sed -e 's/"/\\"/g' -e "s/%quote%/'/g")
        echo -n '    "'$ID'": {
        "RECORD": "'$RECORD'",
        "TYPE": "'$TYPE'",
        "PRIORITY": "'$PRIORITY'",
        "VALUE": "'$VALUE'",
        "ID": "'$ID'",
        "SUSPENDED": "'$SUSPENDED'",
        "TIME": "'$TIME'",
        "DATE": "'$DATE'"
    }'
        if [ "$i" -lt "$objects" ]; then
            echo ','
        else
            echo
        fi
        ((i++))
    done < <(cat $USER_DATA/dns/$domain.conf)
    echo '}'
}

# SHELL list function
shell_list() {
    IFS=$'\n'
    echo "ID^RECORD^TYPE^VALUE^DATE"
    echo "--^------^----^-----^----"
    while read str; do
        eval $str
        echo "$ID^$RECORD^$TYPE^${VALUE:0:30}^$DATE"
    done < <(cat $USER_DATA/dns/$domain.conf)
}

# PLAIN list function
plain_list() {
    IFS=$'\n'
    while read str; do
        eval $str
        VALUE=$(echo "$VALUE" |sed -e "s/%quote%/\\'/g")
        echo -ne "$ID\t$RECORD\t$TYPE\t$PRIORITY\t$VALUE\t"
        echo -e "$SUSPENDED\t$TIME\t$DATE"
    done < <(cat $USER_DATA/dns/$domain.conf)
}

# CSV list function
csv_list() {
    IFS=$'\n'
    echo "ID,RECORD,TYPE,PRIORITY,VALUE,SUSPENDED,TIME,DATE"
    while read str; do
        eval $str
        VALUE=$(echo "$VALUE" |sed -e "s/%quote%/\\'/g")
        echo -n "$ID,$RECORD,$TYPE,$PRIORITY,\"$VALUE\","
        echo "$SUSPENDED,$TIME,$DATE"
    done < <(cat $USER_DATA/dns/$domain.conf)
}


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

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


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

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


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

exit
