#!/bin/bash
# info: change web domain ip address
# options: USER DOMAIN IP [RESTART]
#
# The call is used for changing the site ip address.


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

# Argument defenition
user=$1
domain=$(idn -t --quiet -u "$2" )
domain_idn=$(idn -t --quiet -a "$domain")
ip=$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 IP [RESTART]'
validate_format 'user' 'domain' 'ip'
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_ip_valid
is_ip_avalable


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

# Define variable for replace
get_domain_values 'web'
ip=$(get_real_ip $ip)
tpl_file="$WEBTPL/$WEB_SYSTEM/$TPL.tpl"
conf="$HOMEDIR/$user/conf/web/$WEB_SYSTEM.conf"
old=$(get_real_ip $IP)
new=$ip
replace_web_config

# Checking SSL
if [ "$SSL" = 'yes' ]; then
    tpl_file="$WEBTPL/$WEB_SYSTEM/$TPL.stpl"
    conf="$HOMEDIR/$user/conf/web/s$WEB_SYSTEM.conf"
    replace_web_config
fi

# Checking proxy
if [ ! -z "$PROXY" ]; then
    tpl_file="$WEBTPL/$PROXY_SYSTEM/$PROXY.tpl"
    conf="$HOMEDIR/$user/conf/web/$PROXY_SYSTEM.conf"
    replace_web_config
fi

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


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

# Update counters
increase_ip_value "$new"
decrease_ip_value "$old"

# Update config
update_object_value 'web' 'DOMAIN' "$domain" '$IP' "$3"

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

# Logging
log_history "changed web domain $domain ip to $3"
log_event "$OK" "$EVENT"

exit
