#!/bin/bash
# info: change domain ssl certificate
# options: USER DOMAIN SSL_DIR [RESTART]
#
# The function changes SSL domain certificate and the key. If ca file present
# it will be replaced as well.


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

# Argument definition
user=$1
domain=$2
domain_idn=$2
restart=$3

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

# Additional argument formatting
format_domain
format_domain_idn


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

check_args '3' "$#" 'USER DOMAIN SSL_DIR [RESTART]'
is_format_valid 'user' 'domain' 'ssl_dir'
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_idn"
is_object_unsuspended 'mail' 'DOMAIN' "$domain_idn"
is_object_value_empty 'mail' 'DOMAIN' "$domain_idn" '$SSL'
is_web_domain_cert_valid

# Perform verification if read-only mode is enabled
check_hestia_demo_mode


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

# Remove old configuration
del_mail_ssl_config

# Create new configuration
add_mail_ssl_config


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

# Restarting mail server
$BIN/v-restart-mail $restart

check_result $? "Mail restart failed" >/dev/null

# Logging
log_history "changed ssl certificate for $domain"
log_event "$OK" "$ARGUMENTS"

exit
