#!/bin/bash
# info: list database
# options: USER DATABASE [FORMAT]
#
# The function for obtaining of all database's parameters.


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

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

# Includes
source $VESTA/func/main.sh

# Json function
json_list_db() {
    i=1
    last_word=$(echo "$fields" | wc -w)
    line=$(grep "DB='$database'" $conf)
    echo '{'
    eval $line
    for field in $fields; do
        eval value=$field
        if [ "$i" -eq 1 ]; then
            echo -e "\t\"$value\": {"
        else
            if [ "$last_word" -eq "$i" ]; then
                echo -e "\t\t\"${field//$/}\": \"${value//,/, }\""
            else
                echo -e "\t\t\"${field//$/}\": \"${value//,/, }\","
            fi
        fi
        (( ++i))
    done
    if [ -n "$value" ]; then
        echo -e "\t}"
    fi
    echo -e '}'
}

# Shell list for single database
shell_list_db() {
    line=$(grep "DB='$database'" $conf)
    eval $line
    for field in $fields; do
        eval key="$field"
        echo "${field//$/}: $key "
    done
}


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

check_args '2' "$#" 'USER DATABASE [FORMAT]'
validate_format 'user' 'database'
is_object_valid 'user' 'USER' "$user"
is_object_valid 'db' 'DB' "$database"


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


# Defining fileds to select
conf=$USER_DATA/db.conf
fields='$DB $DBUSER $HOST $TYPE $CHARSET $U_DISK $SUSPENDED $TIME $DATE'

# Listing database
case $format in 
    json)   json_list_db ;;
    plain)  shell_list_db ;;
    shell)  shell_list_db | column -t ;;
    *)      check_args '2' '0' 'USER DATABASE [FORMAT]'
esac


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

exit
