#!/bin/bash
# info: delete web domain alias
# options: USER DOMAIN ALIAS [RESTART]
#
# The function of deleting the alias domain (parked domain). By this call
# default www aliase can be removed as well.


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

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

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


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

check_args '3' "$#" 'USER DOMAIN DOM_ALIAS [RESTART]'
is_format_valid 'user' 'domain' 'dom_alias'
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"
get_domain_values 'web'
if [ -z "$(echo $ALIAS |tr ',' '\n' |grep ^$dom_alias$)" ]; then
    check_result $E_NOTEXIST "alias $dom_alias doesn't exist"
fi


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

# Preparing domain values for the template substitution
local_ip=$(get_real_ip $IP)
ALIAS=$(echo "$ALIAS" |\
    sed -e "s/,/\n/g"|\
    sed -e "s/^$dom_alias$//g"|\
    sed -e "/^$/d"|\
    sed -e ':a;N;$!ba;s/\n/,/g')
prepare_web_domain_values

# Rebuilding vhost
del_web_config "$WEB_SYSTEM" "$TPL.tpl"
add_web_config "$WEB_SYSTEM" "$TPL.tpl"
if [ "$SSL" = 'yes' ]; then
    del_web_config "$WEB_SYSTEM" "$TPL.stpl"
    add_web_config "$WEB_SYSTEM" "$TPL.stpl"
fi

# Rebuilding proxy configuration
if [ ! -z "$PROXY_SYSTEM" ] && [ ! -z "$PROXY" ]; then
    del_web_config "$PROXY_SYSTEM" "$PROXY.tpl"
    add_web_config "$PROXY_SYSTEM" "$PROXY.tpl"
    if [ "$SSL" = 'yes' ]; then
        del_web_config "$PROXY_SYSTEM" "$PROXY.stpl"
        add_web_config "$PROXY_SYSTEM" "$PROXY.stpl"
    fi
fi


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

# Update config
update_object_value 'web' 'DOMAIN' "$domain" '$ALIAS' "$ALIAS"
decrease_user_value "$user" '$U_WEB_ALIASES'

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

$BIN/v-restart-proxy $restart
check_result $? "Proxy restart failed" >/dev/null

# Logging
log_history "deleted alias $dom_alias on $domain"
log_event "$OK" "$ARGUMENTS"

exit
