#!/bin/bash
# info: unsuspend mail domain
# options: USER DOMAIN
#
# example: v-unsuspend-mail-domain user02 acme.com
#
# This function unsuspends mail domain.

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

# Argument definition
user=$1
domain=$2
domain_idn=$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
# load config file
source_conf "$HESTIA/conf/hestia.conf"

# Additional argument formatting
format_domain
format_domain_idn
# TODO: $domain_idn not used in this script - maybe $domain should be converted to $doman_idn ?

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

check_args '2' "$#" 'USER DOMAIN [RESTART]'
is_format_valid 'user' 'domain' 'restart'
is_system_enabled "$MAIL_SYSTEM" 'MAIL_SYSTEM'
is_object_valid 'user' 'USER' "$user"
is_object_valid 'mail' 'DOMAIN' "$domain"
is_object_suspended 'mail' 'DOMAIN' "$domain"

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

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

# Add symbolic link
if [[ "$MAIL_SYSTEM" =~ exim ]]; then
	ln -s $HOMEDIR/$user/conf/mail/$domain /etc/$MAIL_SYSTEM/domains/
fi

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

# Updating config
update_object_value 'mail' 'DOMAIN' "$domain" '$SUSPENDED' 'no'
sed -i "s/SUSPENDED='yes'/SUSPENDED='no'/g" $USER_DATA/mail/$domain.conf
decrease_user_value "$user" '$SUSPENDED_MAIL'

# Enable webmail access
if [ -n "$IMAP_SYSTEM" ]; then
	if [ -n "$WEBMAIL_SYSTEM" ]; then
		for client in ${WEBMAIL_SYSTEM//,/ }; do
			webmail="$client"
		done
		$BIN/v-add-mail-domain-webmail "$user" "$domain" "$webmail" "$restart"
	fi
fi
# Logging
$BIN/v-log-action "system" "Info" "Mail" "Unsuspended mail domain (User: $user, Domain: $domain)."
log_event "$OK" "$ARGUMENTS"

exit
