#!/bin/bash
# info: change web domain template
# options: USER DOMAIN TEMPLATE [RESTART]
#
# The function changes template of the web configuration file. The content
# of webdomain directories remains untouched.


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

# Argument definition
user=$1
domain=$2
domain_idn=$2
template=$3
restart=$4

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

# Additional argument formatting
format_domain
format_domain_idn
# TODO: $domain_idn not used in this script - maybe $domain should be converted to $doman_idn ?


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

check_args '3' "$#" 'USER DOMAIN TEMPLATE [RESTART]'
is_format_valid 'user' 'domain' 'template'
is_system_enabled "$WEB_SYSTEM" 'WEB_SYSTEM'
is_object_valid 'user' 'USER' "$user"
is_object_unsuspended 'user' 'USER' "$user"
is_object_valid 'web' 'DOMAIN' "$domain"
is_object_unsuspended 'web' 'DOMAIN' "$domain"
is_web_template_valid "$template"

# Perform verification if read-only mode is enabled
check_hestia_demo_mode


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

# Parsing domain values
get_domain_values 'web'
local_ip=$(get_real_ip $IP)

# Deleting domain
del_web_config "$WEB_SYSTEM" "$TPL.tpl"
if [ "$SSL" = 'yes' ]; then
    del_web_config "$WEB_SYSTEM" "$TPL.stpl"
fi

# Defining variables for new vhost config
prepare_web_domain_values
add_web_config "$WEB_SYSTEM" "$template.tpl"
if [ "$SSL" = 'yes' ]; then
    add_web_config "$WEB_SYSTEM" "$template.stpl"
fi


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

# Changing tpl in config
update_object_value 'web' 'DOMAIN' "$domain" '$TPL' "$template"

# Restarting web
$BIN/v-restart-web $restart
check_result $? "Web restart failed" >/dev/null

# Logging
log_history "changed web domain template for $domain to $template" '' 'admin'
log_event "$OK" "$ARGUMENTS"

exit
