#!/bin/bash
# info: list web templates
# options: user [format]
#
# The function for obtaining the list of apache templates available to a user.


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

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

# Includes
source $VESTA/func/main.sh

# Json function
json_list_wtpl() {
    i=1
    echo '{'
    for template in $(echo "$templates" |sed -e "s/,/\n/g"); do
        if [ -e "$WEBTPL/apache_$template.descr" ]; then
            descr=$(cat $WEBTPL/apache_$template.descr | grep '#'|\
                sed -e ':a;N;$!ba;s/\n/ /g')
            if [ $i -ne 1 ]; then
                echo -e "\t},"
            fi
            echo -e  "\t\"$template\": {"
            echo -e "\t\t\"DESCR\": \"${descr//# /}\""
            (( ++i))
        fi
    done
    if [ -n "$template" ]; then
        echo -e "\t}"
    fi
    echo '}'
}

# Shell function
shell_list_wtpl() {
    for template in $(echo "$templates" |sed -e "s/,/\n/g"); do
        if [ -e "$WEBTPL/apache_$template.descr" ]; then
            tpl_descr=$(cat $WEBTPL/apache_$template.descr |grep '#')
            if [ -z "$nohead" ]; then
                echo "----------"
            fi
            echo "TEMPLATE: $template"
            echo "DESCRIPTION: ${tpl_descr//# /}"
        fi
    done
}


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

check_args '1' "$#" 'user'
validate_format 'user'
is_object_valid 'user' 'USER' "$user"


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

# Get user package package
templates=$(get_user_value '$WEB_TPL')

# Listing domains
case $format in
    json)   json_list_wtpl ;;
    plain)  nohead=1; shell_list_wtpl ;;
    shell)  shell_list_wtpl ;;
    *)      check_args '1' '0' '[format]'
esac


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

exit
