#!/bin/bash
# info: rebuild mail domain
# options: USER DOMAIN
#
# The function rebuilds configuration files for a single domain.


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

# Argument definition
user=$1
domain=$2

# Includes
source $HESTIA/func/main.sh
source $HESTIA/func/domain.sh
source $HESTIA/func/rebuild.sh
source $HESTIA/func/ip.sh
source $HESTIA/conf/hestia.conf

# Define mail user
if [ "$MAIL_SYSTEM" = 'exim4' ]; then
    MAIL_USER=Debian-exim
else
    MAIL_USER=exim
fi

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

check_args '2' "$#" 'USER DOMAIN'
is_format_valid 'user' 'domain'
is_system_enabled "$MAIL_SYSTEM" 'MAIL_SYSTEM'
is_object_valid 'user' 'USER' "$user"
is_object_unsuspended 'user' 'USER' "$user"
is_object_valid 'mail' 'DOMAIN' "$domain"

if [ "$MAIL_SYSTEM" = 'remote' ]; then
    exit
fi


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

# Rebuild mail domain configuration
rebuild_mail_domain_conf

# Rebuild webmail configuration
if [ ! -z "$WEB_SYSTEM" ] || [ ! -z "$PROXY_SYSTEM" ]; then
    if [ ! -z "$IMAP_SYSTEM" ]; then
        $BIN/v-delete-sys-webmail $user $domain '' 'yes'
        $BIN/v-add-sys-webmail $user $domain '' 'yes'
    fi
fi

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

# Update disk usage statistics
$BIN/v-update-user-disk $user

# Logging
log_event "$OK" "$ARGUMENTS"

exit
