#!/bin/bash
# info: deleting web domain proxy configuration
# options: USER DOMAIN
#
# The function of deleting the virtualhost proxy 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/func/main.sh
source $VESTA/func/domain.sh
source $VESTA/conf/vesta.conf


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

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


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

# Defining domain parameters
get_domain_values 'web'
tpl_file="$WEBTPL/$PROXY_SYSTEM/$PROXY.tpl"
conf="$HOMEDIR/$user/conf/web/$PROXY_SYSTEM.conf"
if [ ! -z "$PROXY_SYSTEM" ]; then
    del_web_config
fi

# Checking SSL
if [ "$SSL" = 'yes' ]; then
    tpl_file="$WEBTPL/$PROXY_SYSTEM/$PROXY.stpl"
    conf="$HOMEDIR/$user/conf/web/s$PROXY_SYSTEM.conf"
    if [ ! -z "$PROXY_SYSTEM" ]; then
        del_web_config
    fi
fi


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

# Update config
update_object_value 'web' 'DOMAIN' "$domain" '$PROXY' ''
update_object_value 'web' 'DOMAIN' "$domain" '$PROXY_EXT' ''

if [ -z "$PROXY_SYSTEM" ]; then
    exit
fi

# Checking last SSL proxy
conf="/etc/$PROXY_SYSTEM/conf.d/vesta.conf"
last_sproxy=$(grep "SSL='yes'" $USER_DATA/web.conf)
if [ -z "$last_sproxy" ]; then
    sed -i "/.*\/$user\/.*s$PROXY_SYSTEM.conf/d" $conf
    rm -f $HOMEDIR/$user/conf/web/s$PROXY_SYSTEM.conf
fi

# Checking last proxy
last_proxy=$(grep -v "PROXY=''" $USER_DATA/web.conf)
if [ -z "$last_proxy" ]; then
    sed -i "/.*\/$user\/.*$PROXY_SYSTEM.conf/d" $conf
    rm -f $HOMEDIR/$user/conf/web/$PROXY_SYSTEM.conf
fi

# Restart proxy server
if [ "$restart" != 'no' ]; then
    $BIN/v-restart-proxy
    if [ $? -ne 0 ]; then
        exit $E_RESTART
    fi
fi

# Logging
log_history "disabled proxy support for $domain"
log_event "$OK" "$EVENT"

exit
