#!/bin/bash
# info: deleting web domain nginx configuration
# options: user domain
#
# The function of deleting the virtualhost nginx configuration.


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

# Argument defenition
user=$1
domain=$(idn -t --quiet -u "$2" )
domain_idn=$(idn -t --quiet -a "$domain")
restart=$3

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


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

check_args '2' "$#" 'user domain'
validate_format 'user' 'domain'
is_system_enabled "$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_object_value_exist 'web' 'DOMAIN' "$domain" '$NGINX'


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

# Defining domain parameters
get_domain_values 'web'
tpl_file="$WEBTPL/ngingx_$NGINX.tpl"
conf="$HOMEDIR/$user/conf/web/nginx.conf"
del_web_config

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


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

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

# Checking last nginx domain
conf='/etc/nginx/conf.d/vesta_users.conf'
last_nginx=$(grep -v "NGINX=''" $USER_DATA/web.conf)
last_snginx=$(echo "$last_nginx" | grep "SSL='yes'")
if [ -z "$last_snginx" ]; then
    sed -i "/$user\/conf\/web\/snginx.conf/d" $conf
    rm -f $HOMEDIR/$user/conf/web/snginx.conf
fi

if [ -z "$last_nginx" ]; then
    sed -i "/$user\/conf\/web\/nginx.conf/d" $conf
    rm -f $HOMEDIR/$user/conf/web/nginx.conf
fi

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

# Logging
log_history "$EVENT"
log_event "$OK" "$EVENT"

exit
