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


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

# Argument defenition
user=$1
domain=$(idn -t --quiet -u "$2" )
domain_idn=$(idn -t --quiet -a "$domain")
template=$3
default_extentions="jpg,jpeg,gif,png,ico,svg,css,zip,tgz,gz,rar,bz2,doc,xls,\
exe,pdf,ppt,txt,odt,ods,odp,odf,tar,wav,bmp,rtf,js,mp3,avi,mpeg,flv,html,htm"
extentions=${4-$default_extentions}
restart="$5"


# Includes
source $VESTA/conf/vesta.conf
source $VESTA/func/main.sh
source $VESTA/func/domain.sh


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

check_args '3' "$#" 'USER DOMAIN TEMPLATE [EXTENTIONS] [RESTART]'
validate_format 'user' 'domain' 'template'
is_system_enabled "$PROXY_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_object_value_exist 'web' 'DOMAIN' "$domain" '$NGINX'
is_nginx_template_valid


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

# Parsing domain values
get_domain_values 'web'
tpl_file="$WEBTPL/nginx_$NGINX.tpl"
conf="$HOMEDIR/$user/conf/web/nginx.conf"

# Delete old vhost
del_web_config

# Checking ssl
if [ "$SSL" = 'yes' ]; then
    tpl_file="$WEBTPL/nginx_$NGINX.stpl"
    conf="$HOMEDIR/$user/conf/web/snginx.conf"
    del_web_config
fi

# Add new vhost
NGINX="$template"
NGINX_EXT="$extentions"
tpl_file="$WEBTPL/nginx_$NGINX.tpl"
conf="$HOMEDIR/$user/conf/web/nginx.conf"
upd_web_domain_values
add_web_config
chown root:nginx $conf
chmod 640 $conf

# Checking ssl
if [ "$SSL" = 'yes' ]; then
    tpl_file="$WEBTPL/nginx_$NGINX.stpl"
    conf="$HOMEDIR/$user/conf/web/snginx.conf"
    add_web_config
    chown root:nginx $conf
    chmod 640 $conf
fi


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

# Update config
update_object_value 'web' 'DOMAIN' "$domain" '$NGINX' "$NGINX"
update_object_value 'web' 'DOMAIN' "$domain" '$NGINX_EXT' "$extentions"

# Restart web
if [ "$restart" != 'no' ]; then
    $BIN/v-restart-web "$EVENT"
fi

# Logging
log_history "changed nginx template for $domain to $template"
log_event "$OK" "$EVENT"

exit
