#!/bin/bash
# info: calculate disk usage for all mail domains
# options: USER
#
# The function calculates disk usage for all mail domains.


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

# Argument definition
user=$1

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


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

check_args '1' "$#" 'USER'
is_format_valid 'user'
is_system_enabled "$MAIL_SYSTEM" 'MAIL_SYSTEM'
is_object_valid 'user' 'USER' "$user"
if [ -z "$MAIL_SYSTEM" ] || [ "$MAIL_SYSTEM" = 'remote' ]; then
    exit
fi


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

# Starting loop
for domain in $(search_objects 'mail' 'SUSPENDED' "no" 'DOMAIN'); do
    dom_diks=0
    accounts=$(search_objects "mail/$domain" 'SUSPENDED' "no" 'ACCOUNT')
    for account in $accounts; do
        home_dir=$HOMEDIR/$user/mail/$domain/$account
        if [ -e "$home_dir" ]; then
            udisk=$(nice -n 19 du -shm $home_dir | cut -f 1 )
        else
            udisk=0
        fi
        update_object_value "mail/$domain" 'ACCOUNT' "$account"  '$U_DISK' "$udisk"
        dom_diks=$((dom_diks + udisk))
    done
    update_object_value 'mail' 'DOMAIN' "$domain" '$U_DISK' "$dom_diks"
done


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


recalc_user_disk_usage

# Logging
log_event "$OK" "$ARGUMENTS"

exit
