#!/bin/bash
# info: change web domain template
# options: USER DOMAIN TEMPLATE [RESTART]
#
# example: v-change-web-domain-tpl admin acme.com opencart
#
# This function changes template of the web configuration file. The content
# of webdomain directories remains untouched.

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

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

# 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
# shellcheck source=/usr/local/hestia/func/domain.sh
source $HESTIA/func/domain.sh
# shellcheck source=/usr/local/hestia/func/ip.sh
source $HESTIA/func/ip.sh
# load config file
source_conf "$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")
export local_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
$BIN/v-log-action "$user" "Info" "Web" "Web domain template applied (Domain: $domain, Template: $template)."
log_event "$OK" "$ARGUMENTS"

exit