#!/bin/bash
# info: update IP usage counters
# options: IP
#
# example: v-update-sys-ip-counters
#
# Function updates usage U_WEB_ADOMAINS and U_SYS_USERS counters.

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

# Argument definition
ip="$1"

# 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/ip.sh
source $HESTIA/func/ip.sh
# load config file
source_conf "$HESTIA/conf/hestia.conf"

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

check_args '0' "$#" 'IP'
if [ -n "$ip" ]; then
	is_format_valid 'ip'
	is_ip_valid
fi

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

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

# Creating user_list
if [ -z "$ip" ]; then
	ip_list="$(ls $HESTIA/data/ips/)"
else
	ip_list="$ip"
fi

# Updating user stats
for ip in $ip_list; do

	# Calculate usage
	ip_usage="$(grep -H "$ip" $HESTIA/data/users/*/web.conf)"
	web_domains="$(echo "$ip_usage" | sed '/^$/d' | wc -l)"
	sys_users="$(echo "$ip_usage" | cut -f7 -d/ | sort -u | tr '\n' ',' | sed "s/,$//g")"

	# Update counters
	update_ip_value '$U_WEB_DOMAINS' "$web_domains"
	update_ip_value '$U_SYS_USERS' "$sys_users"
done

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

# Logging
log_event "$OK" "$ARGUMENTS"

exit