#!/bin/bash
# info: update web templates
# options: [RESTART] [SKIP]
#
# The function for obtaining updated pack of web templates.


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

# Argument definition
restart=$1
skip=$2

# Includes
source $HESTIA/func/main.sh
source $HESTIA/conf/hestia.conf

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

# Update templates
if [ -d "${WEBTPL}" ]; then
    rm -rf "${WEBTPL}/skel" 2>/dev/null
    rm -rf "${WEBTPL}/suspend" 2>/dev/null
    rm -rf "${WEBTPL}/unassigned" 2>/dev/null
fi

[ -d "${WEBTPL}/nginx" ] || mkdir -p "${WEBTPL}/nginx"

if [ "$PROXY_SYSTEM" = 'nginx' ] || [ "$WEB_BACKEND" = "php-fpm" ]; then
    cp -rf "${HESTIA_INSTALL_DIR}/templates/web/nginx" "${WEBTPL}/"
fi

for webtpl_folder in $(ls $HESTIA_INSTALL_DIR/templates/web/* -d 2>/dev/null | egrep -v '/(nginx)$' ); do
    cp -rf "${webtpl_folder}" "${WEBTPL}/"
done

for php_ver in $(ls /etc/php/); do
    [ ! -d "/etc/php/$php_ver/fpm/pool.d/" ] && continue
    cp -f "$HESTIA_INSTALL_DIR/php-fpm/multiphp.tpl"  ${WEBTPL}/php-fpm/PHP-${php_ver/\./_}.tpl
done

# Rebuilding web domains
if [ ! -z "$skip" ]; then
    for user in $($BIN/v-list-sys-users plain); do
        $BIN/v-rebuild-web-domains $user no
    done
fi

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

# Restarting web server
$BIN/v-restart-web $restart
check_result $? "restart" >/dev/null 2>&1

$BIN/v-restart-proxy $restart
check_result $? "restart" >/dev/null 2>&1

exit
