#!/bin/bash
# info: update domain bandwidth usage
# options: USER DOMAIN
#
# example: v-update-web-domain-traff admin example.com
#
# This function recalculates bandwidth usage for specific domain.

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

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

# 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'
is_format_valid 'user' 'domain'
is_system_enabled "$WEB_SYSTEM" 'WEB_SYSTEM'
is_object_valid 'user' 'USER' "$user"
is_object_unsuspended 'user' 'USER' "$user"
is_object_valid 'web' 'DOMAIN' "$domain"
is_object_unsuspended 'web' 'DOMAIN' "$domain"

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

# Defining log file
log_file="/var/log/$WEB_SYSTEM/domains/$domain.bytes"

# Defining bytes
bytes=0

# Parsing log
while read line; do
	if [[ "$line" =~ ^[0-9]+$ ]]; then
		line=${line#0}
		if [ -n "$line" ]; then
			bytes=$(($bytes + $line))
		fi
	fi
done < $log_file

# Converting to Mb
mb=$(echo "$bytes / 1024 / 1024" | bc)

# Nulling log
echo > $log_file

# Reset counter on the start of the month
if [ "$(date +%d)" = '01' ]; then
	update_object_value 'web' 'DOMAIN' "$domain" '$U_BANDWIDTH' '0'
fi

# Parsing old value
get_domain_values 'web'

# Defining new value
bandwidth=$((U_BANDWIDTH + mb))

# Updating bandwidth value in config
update_object_value 'web' 'DOMAIN' "$domain" '$U_BANDWIDTH' "$bandwidth"

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

# Logging
log_event "$OK" "$ARGUMENTS"

exit