#!/bin/bash
# info: rebuild mail domains
# options: USER
#
# The function rebuilds EXIM configuration files for all mail domains.


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

# Argument defenition
user=$1

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


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

check_args '1' "$#" 'USER'
validate_format 'user'
is_system_enabled "$MAIL_SYSTEM" 'MAIL_SYSTEM'
is_object_valid 'user' 'USER' "$user"
is_object_unsuspended 'user' 'USER' "$user"
if [ "$MAIL_SYSTEM" = 'remote' ]; then
    exit
fi


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

# Reset counters
U_MAIL_DOMAINS=0
U_MAIL_DKMI=0
U_MAIL_ACCOUNTS=0
SUSPENDED_MAIL=0
U_DISK_MAIL=0

# Checking mail folder
if [ ! -d "$USER_DATA/mail" ]; then
    rm -f $USER_DATA/mail
    mkdir $USER_DATA/mail
fi

# Starting loop
for domain in $(search_objects 'mail' 'SUSPENDED' "*" 'DOMAIN'); do
    rebuild_mail_domain_conf
done


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

# Updating counters
update_user_value "$user" '$U_MAIL_DOMAINS' "$U_MAIL_DOMAINS"
update_user_value "$user" '$U_MAIL_DKMI' "$U_MAIL_DKMI"
update_user_value "$user" '$U_MAIL_ACCOUNTS' "$U_MAIL_ACCOUNTS"
update_user_value "$user" '$SUSPENDED_MAIL' "$SUSPENDED_MAIL"
update_user_value "$user" '$U_DISK_MAIL' "$U_DISK_MAIL"

recalc_user_disk_usage

# Logging
log_event "$OK" "$EVENT"

exit
