#!/bin/bash
# info: add system wide smtp relay support
# options: HOST [USERNAME] [PASSWORD] [PORT]
#
# example: v-add-sys-smtp-relay srv.smtprelay.tld uname123 pass12345
#
# This function adds system wide smtp relay support.

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

# Argument definition
host=$1
username=$2
password=$3
port=${4-587}

# 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 '1' "$#" 'HOST [USERNAME] [PASSWORD] [PORT]'
is_format_valid 'port' 'host' 'password'
is_username_format_valid "$username" 'username'
format_no_quotes "$password" 'passowrd'
is_system_enabled "$MAIL_SYSTEM" 'MAIL_SYSTEM'

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

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

change_sys_value 'SMTP_RELAY' 'true'
change_sys_value 'SMTP_RELAY_HOST' "$host"
change_sys_value 'SMTP_RELAY_PORT' "$port"
change_sys_value 'SMTP_RELAY_USER' "$username"

cat > /etc/exim4/smtp_relay.conf << EOL
host:$host
port:$port
user:$username
pass:$password
EOL

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

# Logging
$BIN/v-log-action "system" "Info" "Mail" "Server-wide SMTP Relay enabled (Host: $host, Port: $port)."
log_event "$OK" "$ARGUMENTS"

exit
