#!/bin/bash
# info: update domains bandwidth usage
# options: user
#
# The function recalculates bandwidth usage for all user webdomains.


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

# Argument defenition
user=$1

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


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

check_args '1' "$#" 'user'
validate_format 'user'
is_system_enabled "$WEB_SYSTEM"
is_object_valid 'user' 'USER' "$user" "$user"
is_object_unsuspended 'user' 'USER' "$user"


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

for domain in $(search_objects 'web' 'SUSPENDED' "no" 'DOMAIN'); do
    log_file="/var/log/httpd/domains/$domain.bytes"
    bytes=0

    # Parsing log
    while read line; do
        if [[ '-' != "$line" ]] && [[ 0 -lt "$line" ]]; then
            bytes=$(($bytes + $line))
        fi
    done < $log_file

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

    # Nulling log
    echo > $log_file

    get_domain_values 'web'
    bandwidth=$((U_BANDWIDTH + mb))

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

done


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

# Recalculating user bandwidth
recalc_user_bandwidth_usage

# No Logging
#log_event "$OK" "$EVENT"

exit
