#!/bin/bash
# info: rebuild web domains
# options: USER [RESTART]
#
# The function rebuilds web configuration files.


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

# Argument definition
user=$1
restart=$2

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


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

check_args '1' "$#" 'USER [RESTART]'
is_format_valid 'user'
is_system_enabled "$WEB_SYSTEM" 'WEB_SYSTEM'
is_object_valid 'user' 'USER' "$user"
is_object_unsuspended 'user' 'USER' "$user"


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

# Deleting old web configs
sed -i "/.*\/$user\/conf\/web\//d" /etc/$WEB_SYSTEM/conf.d/vesta.conf
if [ -e "$HOMEDIR/$user/conf/web/$WEB_SYSTEM.conf"  ]; then
    rm $HOMEDIR/$user/conf/web/$WEB_SYSTEM.conf
fi
if [ -e "$HOMEDIR/$user/conf/web/s$WEB_SYSTEM.conf" ]; then
    rm $HOMEDIR/$user/conf/web/s$WEB_SYSTEM.conf
fi

# Deleting old proxy configs
if [ ! -z "$PROXY_SYSTEM" ]; then
    sed -i "/.*\/$user\/conf\/web\//d" /etc/$PROXY_SYSTEM/conf.d/vesta.conf

    if [ -e "$HOMEDIR/$user/conf/web/$PROXY_SYSTEM.conf" ]; then
        rm $HOMEDIR/$user/conf/web/$PROXY_SYSTEM.conf
    fi

    if [ -e "$HOMEDIR/$user/conf/web/s$PROXY_SYSTEM.conf" ]; then
        rm $HOMEDIR/$user/conf/web/s$PROXY_SYSTEM.conf
    fi
fi

# Deleting backend configs
if [ ! -z "$WEB_BACKEND" ]; then
    if [ "$WEB_BACKEND_POOL" = 'user' ]; then
        prepare_web_backend
        rm -f $pool/$backend_type.conf
    else
        for domain in $($BIN/v-list-web-domains $user plain |cut -f 1); do
            prepare_web_backend
            rm -f $pool/$backend_type.conf
        done
    fi
fi

# Starting rebuild loop for each web domain
for domain in $($BIN/v-list-web-domains $user plain |cut -f 1); do
    if [ ! -z "$WEB_BACKEND" ]; then
        template=$(get_object_value 'web' 'DOMAIN' "$domain" '$BACKEND')
        $BIN/v-add-web-domain-backend $user $domain $template $restart
    fi
    rebuild_web_domain_conf
done


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

# Updating user counters
$BIN/v-update-user-counters $user

# 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_event "$OK" "$ARGUMENTS"

exit
