#!/bin/bash
# info: add web domain alias
# options: USER DOMAIN ALIASES [RESTART]
#
# The call is intended for adding aliases to a domain (it is also called
# "domain parking"). The function supports wildcards *.domain.tpl.


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

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

# Includes
source $VESTA/func/main.sh
source $VESTA/func/domain.sh
source $VESTA/func/ip.sh
source $VESTA/conf/vesta.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 ?
format_aliases


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

check_args '3' "$#" 'USER DOMAIN ALIASES [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"
is_domain_new 'web' "$aliases"
is_package_full 'WEB_ALIASES'


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

# Parsing domain values
get_domain_values 'web'

# Preparing domain values for the template substitution
local_ip=$(get_real_ip $IP)
if [ -z "$ALIAS" ]; then
    ALIAS="$aliases"
else
    ALIAS="$ALIAS,$aliases"
fi
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                              #
#----------------------------------------------------------#

# Adding new alias
update_object_value 'web' 'DOMAIN' "$domain" '$ALIAS' "$ALIAS"
increase_user_value "$user" '$U_WEB_ALIASES'

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

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


log_history "added $aliases for $domain"
log_event "$OK" "$ARGUMENTS"

exit
