#!/bin/bash
# info: list system ips
# options: [FORMAT]
#
# The function for obtaining the list of system ip's.


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

# Argument defenition
format=${1-shell}

# Includes
source $VESTA/func/main.sh

# Json function
json_list_ips() {
    echo '{'
    ip_list=$(ls $VESTA/data/ips/)
    fileds_count=$(echo "$fields" | wc -w)
    for IP in $ip_list; do
        ip_data=$(cat $VESTA/data/ips/$IP)
        eval $ip_data
        if [ -n "$data" ]; then
            echo -e '        },'
        fi
        i=1
        for field in $fields; do
            eval value=$field
            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
    if [ -n "$data" ]; then
        echo -e '        }'
    fi
    echo -e '}'
}

# Shell function
shell_list_ips() {
    ip_list=$(ls $VESTA/data/ips/)
    if [ -z "$nohead" ]; then
        echo "${fields//$/}"
        for a in $fields; do
            echo -e "--------- \c"
        done
        echo
    fi

    for IP in $ip_list; do
        source $VESTA/data/ips/$IP
        for field in $fields; do
            eval value=$field
            if [ -z "$value" ]; then
                value='NULL'
            fi
            echo -n "$value "
        done
        echo
    done
}


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

# Defining fileds to select
conf=$VESTA/data/ips/*
fields="\$IP \$OWNER \$STATUS \$NAME \$U_SYS_USERS \$U_WEB_DOMAINS"
fields="$fields \$INTERFACE \$NETMASK \$NAT \$TIME \$DATE"

# Listing ip addresses
case $format in 
    json)   json_list_ips ;;
    plain)  nohead=1; shell_list_ips ;;
    shell)  fields='$IP $NETMASK $NAT $OWNER $U_WEB_DOMAINS';
            shell_list_ips | column -t ;;
    *)      check_args '1' '0' '[FORMAT]'
esac


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

exit
