#!/bin/bash
# info: add web domain backend
# options: USER DOMAIN [TEMPLATE] [RESTART]
#
# The call is used for adding web backend configuration.


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

# Argument definition
user=$1
domain=$2
template=${3-default}
restart=$4

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


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

check_args '2' "$#" 'USER DOMAIN [TEMPLATE] [RESTART]'
is_system_enabled "$WEB_BACKEND" 'WEB_BACKEND'
is_object_valid 'user' 'USER' "$user"
is_object_unsuspended 'user' 'USER' "$user"
is_backend_template_valid "$template"


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

# Defining pool directory
prepare_web_backend

# Checking backend configuration
if [ -e "$pool/$backend_type.conf" ]; then
    exit
fi

# Allocating backend port
backend_port=9000
ports=$(grep -v '^;' $pool/* 2>/dev/null |grep listen |grep -o :[0-9].*)
ports=$(echo "$ports" |sed "s/://" |sort -n)
for port in $ports; do
    if [ "$backend_port" -eq "$port" ]; then
        backend_port=$((backend_port + 1))
    fi
done

# Adding backend config
cat $WEBTPL/$WEB_BACKEND/$template.tpl |\
    sed -e "s|%backend_port%|$backend_port|" \
        -e "s|%user%|$user|g"\
        -e "s|%domain%|$domain|g"\
        -e "s|%backend%|$backend_type|g" > $pool/$backend_type.conf


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

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

# Logging
log_history "added $WEB_BACKEND backend configuration for $domain"
log_event "$OK" "$ARGUMENTS"

exit