#!/bin/bash
# info: deleting web domain backend configuration
# options: USER DOMAIN [RESTART]
#
# example: v-delete-web-domain-backend admin acme.com
#
# This function of deleting the virtualhost backend configuration.

#----------------------------------------------------------#
#                Variables & Functions                     #
#----------------------------------------------------------#

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

# Includes
# shellcheck source=/etc/hestiacp/hestia.conf
source /etc/hestiacp/hestia.conf
# shellcheck source=/usr/local/hestia/func/main.sh
source $HESTIA/func/main.sh
# shellcheck source=/usr/local/hestia/func/domain.sh
source $HESTIA/func/domain.sh
# load config file
source_conf "$HESTIA/conf/hestia.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 ?

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

check_args '2' "$#" 'USER DOMAIN [RESTART]'
is_format_valid 'user' 'domain'
is_system_enabled "$WEB_SYSTEM" 'WEB_SYSTEM'
is_object_valid 'user' 'USER' "$user"
is_object_valid 'web' 'DOMAIN' "$domain"

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

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

get_domain_values 'web'
BACKEND="$template"

# Defining pool directory
if [ -f "/etc/redhat-release" ]; then
	pool=$(find -L /etc/opt/remi/ -name "$domain.conf" -exec dirname {} \;)
else
	pool=$(find -L /etc/php/ -name "$domain.conf" -exec dirname {} \;)
fi
if [ ! -e "$pool" ]; then
	check_result "$E_NOTEXIST" "php-fpm pool doesn't exist"
fi

# Defining backend type
backend_type="$domain"
if [ "$WEB_BACKEND_POOL" = 'user' ]; then
	backend_type="$user"
fi

# Checking last webdomain
if [ "$WEB_BACKEND_POOL" = 'user' ]; then
	domains=$(search_objects 'web' 'SUSPENDED' "no" 'DOMAIN' | wc -l)
	if [ "$backend_type" = "$user" ] && [ "$domains" -gt 1 ]; then
		exit
	fi
fi

# Deleting backend
delete_web_backend

#----------------------------------------------------------#
#                       Hestia                             #
#----------------------------------------------------------#

# Detect prev version
if [[ $BACKEND =~ ^.*PHP-([0-9])\_([0-9])$ ]]; then
	version="${BASH_REMATCH[1]}.${BASH_REMATCH[2]}"
else
	version=$(multiphp_default_version)
fi
# Restarting php interpreter
$BIN/v-restart-web-backend "$restart" "$version"
check_result $? "PHP restart failed" > /dev/null

# Logging
$BIN/v-log-action "$user" "Info" "Web" "Web domain configuration deleted (Domain: $domain)."
log_event "$OK" "$ARGUMENTS"

exit