#!/bin/bash
# info: disable web domain stats authentication support
# options: USER DOMAIN [RESTART]
#
# example: v-delete-web-domain-stats-user admin acme.com
#
# This function removes authentication of statistics system. If the script is
# called without naming a certain user, all users will be removed. After
# deleting all of them statistics will be accessible for view without an
# authentication.

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

# Argument definition
user=$1
domain=$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"

#----------------------------------------------------------#
#                    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"
is_object_value_exist 'web' 'DOMAIN' "$domain" '$STATS_USER'

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

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

# Deleting statistic dir
stats_dir="$HOMEDIR/$user/web/$domain/stats"
rm -f "$stats_dir/.htpasswd"
rm -f "$stats_dir/.htaccess"

# Deleting nginx auth config
if [ "$WEB_SYSTEM" = 'nginx' ]; then
	rm -f $stats_dir/auth.conf 2> /dev/null
	$BIN/v-restart-web "$restart"
	check_result $? "Web restart failed" > /dev/null
fi

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

# Update config
update_object_value 'web' 'DOMAIN' "$domain" '$STATS_USER' ''
update_object_value 'web' 'DOMAIN' "$domain" '$STATS_CRYPT' ''

# Logging
$BIN/v-log-action "$user" "Info" "Web" "Web traffic analyzer password enabled (Domain: $domain)."
log_event "$OK" "$ARGUMENTS"

exit
