#!/bin/bash
# info: list system user
# options: USER [FORMAT]
#
# The function for obtainig the list of all user's parameters.


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

# Includes
source $VESTA/func/main.sh

# Argument defenition
user=$1
USER="$user"
format=${2-shell}

# Json function
json_list_user() {
    i=1
    fileds_count=$(echo "$fields" | wc -w)
    source $VESTA/data/users/$user/user.conf
    echo '{'
    for field in $fields; do
        eval value=$field
        if [ "$i" -eq 1 ]; then
            echo -e "\t\"$value\": {"
        else
            if [ "$fileds_count" -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 '        }'
    fi
    echo -e "}"
}

# Shell function
shell_list_user() {
    source $VESTA/data/users/$user/user.conf
    for field in $fields; do
        eval key="$field"
        if [ -z "$key" ]; then
            key='NULL'
        fi
        echo "${field//$/}: $key "
    done
}


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

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


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

# Defining config
conf=$USER_DATA/user.conf
HOME=$HOMEDIR/$user

# Defining fileds to select
fields='$USER $FNAME $LNAME $PACKAGE $WEB_TEMPLATE $PROXY_TEMPLATE
    $DNS_TEMPLATE $WEB_DOMAINS $WEB_ALIASES $DNS_DOMAINS $DNS_RECORDS
    $MAIL_DOMAINS $MAIL_ACCOUNTS $DATABASES $CRON_JOBS $DISK_QUOTA $BANDWIDTH
    $NS $SHELL $BACKUPS $CONTACT $CRON_REPORTS $RKEY $SUSPENDED
    $SUSPENDED_USERS $SUSPENDED_WEB $SUSPENDED_DNS $SUSPENDED_MAIL
    $SUSPENDED_DB $SUSPENDED_CRON $IP_AVAIL $IP_OWNED $U_USERS $U_DISK
    $U_DISK_DIRS $U_DISK_WEB $U_DISK_MAIL $U_DISK_DB $U_BANDWIDTH
    $U_WEB_DOMAINS $U_WEB_SSL $U_WEB_ALIASES $U_DNS_DOMAINS $U_DNS_RECORDS
    $U_MAIL_DOMAINS $U_MAIL_DKIM $U_MAIL_ACCOUNTS $U_DATABASES $U_CRON_JOBS
    $U_BACKUPS $LANGUAGE $HOME $TIME $DATE'

# Listing user
case $format in 
    json)   json_list_user ;;
    plain)  nohead=1; shell_list_user ;;
    shell)  shell_list_user | column -t ;;
esac


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

exit
