#!/bin/bash
# info: Add SMTP Account for logging, notification and internal mail
# options: DOMAIN PORT SMTP_SECURITY USERNAME PASSWORD EMAIL
#
# example: v-add-sys-smtp example.com 587 STARTTLS test@domain.com securepassword test@example.com
#
# This function allows configuring a SMTP account for the server to use
# for logging, notification and warn emails etc.

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

# Argument definition
domain=$1
port=$2
smtp_security=$3
username=$4
password=$5
email=$6

# 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
# load config file
source_conf "$HESTIA/conf/hestia.conf"

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

check_args '6' "$#" 'DOMAIN PORT SMTP_SECURITY USERNAME PASSWORD EMAIL'
is_format_valid 'domain' 'port' 'email' 'password'
is_username_format_valid "$username" 'username'
format_no_quotes "$password" 'passowrd'
is_common_format_valid "$smtp_security" "SMTP_SECURITY"

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

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

change_sys_value "USE_SERVER_SMTP" 'true'
change_sys_value "SERVER_SMTP_HOST" "$domain"
change_sys_value "SERVER_SMTP_PORT" "$port"
change_sys_value "SERVER_SMTP_SECURITY" "$smtp_security"
change_sys_value "SERVER_SMTP_USER" "$username"
change_sys_value "SERVER_SMTP_PASSWD" "$password"
change_sys_value "SERVER_SMTP_ADDR" "$email"

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

# Logging
$BIN/v-log-action "system" "Info" "Mail" "Server SMTP enabled."
log_event "$OK" "$ARGUMENTS"

exit
