#!/bin/bash
# info: rebuild mail domain
# options: USER DOMAIN
#
# example: v-rebuild-mail-domain user domain.tld
#
# This function rebuilds configuration files for a single domain.

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

# Argument definition
user=$1
domain=$2
restart=${3-yes}

# 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
# shellcheck source=/usr/local/hestia/func/ip.sh
source $HESTIA/func/ip.sh
# shellcheck source=/usr/local/hestia/func/rebuild.sh
source $HESTIA/func/rebuild.sh
# shellcheck source=/usr/local/hestia/func/syshealth.sh
source $HESTIA/func/syshealth.sh
# load config file
source_conf "$HESTIA/conf/hestia.conf"

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

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

check_args '2' "$#" 'USER DOMAIN'
is_format_valid 'user' 'domain' 'restart'
is_system_enabled "$MAIL_SYSTEM" 'MAIL_SYSTEM'
is_object_valid 'user' 'USER' "$user"
check_user=$(is_object_unsuspended 'user' 'USER' "$user")
if [ -n "$check_user" ]; then
	exit
fi
is_object_valid 'mail' 'DOMAIN' "$domain"

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

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

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

# Rebuild mail domain configuration
rebuild_mail_domain_conf

# Rebuild webmail configuration
if [ -n "$WEB_SYSTEM" ] || [ -n "$PROXY_SYSTEM" ]; then
	if [ -n "$IMAP_SYSTEM" ]; then
		WEBMAIL=$(get_object_value 'web' 'DOMAIN' "$domain" "$WEBMAIL")
		if [ -n "$WEBMAIL" ]; then
			$BIN/v-delete-mail-domain-webmail "$user" "$domain" "$restart" 'yes'
			$BIN/v-add-mail-domain-webmail "$user" "$domain" "$WEBMAIL" "$restart" 'yes'
		fi
	fi
fi

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

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

# Logging
$BIN/v-log-action "system" "Info" "System" "Rebuilt mail domain (User: $user, Domain: $domain)."
log_event "$OK" "$ARGUMENTS"

exit