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

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

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

# 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

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

check_args '3' "$#" 'USER DOMAIN SSL_DIR [RESTART]'
is_format_valid 'user' 'domain' 'ssl_dir' 'restart'
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_exist '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
$BIN/v-log-action "$user" "Info" "Mail" "SSL certificate changed (Domain: $domain)."
log_event "$OK" "$ARGUMENTS"

exit
