#!/bin/bash
# info: list user backup
# options: USER BACKUP [FORMAT]
#
# example: v-list-user-backup admin admin.2019-05-19_03-31-30.tar
#
# This function of obtaining the list of backup parameters. This call, just as
# all v_list_* calls, supports 3 formats - json, shell and plain.

#----------------------------------------------------------#
#                Variables & Functions                     #
#----------------------------------------------------------#

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

# Includes
# shellcheck source=/etc/hestiacp/hestia.conf
source /etc/hestiacp/hestia.conf
# shellcheck source=/usr/local/hestia/func/main.sh
source $HESTIA/func/main.sh
# load config file
source_conf "$HESTIA/conf/hestia.conf"

fields="\$BACKUP \$TYPE \$SIZE \$WEB \$DNS \$DB \$MAIL \$CRON \$UDIR"
fields="$fields \$RUNTIME \$TIME \$DATE"

# JSON list function
json_list() {
	echo '{'
	echo '    "'$BACKUP'": {
        "TYPE": "'$TYPE'",
        "SIZE": "'$SIZE'",
        "WEB": "'$WEB'",
        "DNS": "'$DNS'",
        "MAIL": "'$MAIL'",
        "DB": "'$DB'",
        "CRON": "'$CRON'",
        "UDIR": "'$UDIR'",
        "RUNTIME": "'$RUNTIME'",
        "TIME": "'$TIME'",
        "DATE": "'$DATE'"
    }'
	echo '}'
}

# SHELL list function
shell_list() {
	echo "BACKUP:         $BACKUP"
	echo "TYPE:           $TYPE"
	echo "SIZE:           $SIZE mb"
	echo "RUNTIME:        $RUNTIME min"
	echo "WEB:            ${WEB//,/ }"
	echo "DNS:            ${DNS//,/ }"
	echo "MAIL:           ${MAIL//,/ }"
	echo "DB:             ${DB//,/ }"
	echo "CRON:           $CRON"
	echo "UDIR:           ${UDIR//,/ }"
	echo "TIME:           $TIME"
	echo "DATE:           $DATE"
}

# PLAIN list function
plain_list() {
	echo -ne "$BACKUP\t$TYPE\t$SIZE\t$WEB\t$DNS\t$MAIL\t$DB\t$CRON\t"
	echo -e "$UDIR\t$RUNTIME\t$TIME\t$DATE"
}

# CSV list function
csv_list() {
	echo "BACKUP,TYPE,SIZE,WEB,DNS,MAIL,DB,CRON,UDIR,RUNTIME,TIME,DATE"
	echo -n "$BACKUP,$TYPE,$SIZE,\"$WEB\",\"$DNS\",\"$MAIL\",\"$DB\","
	echo "\"$CRON\",\"$UDIR\",$RUNTIME,$TIME,$DATE"
}

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

check_args '2' "$#" 'USER BACKUP [FORMAT]'
is_format_valid 'user' 'backup'
is_object_valid 'user' 'USER' "$user"
is_object_valid 'backup' 'BACKUP' "$backup"

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

# Parsing backup config
parse_object_kv_list $(grep "BACKUP='$backup'" $USER_DATA/backup.conf)

# Listing data
case $format in
	json) json_list ;;
	plain) plain_list ;;
	csv) csv_list ;;
	shell) shell_list ;;
esac

#----------------------------------------------------------#
#                       Hestia                             #
#----------------------------------------------------------#

exit
