#!/bin/bash
# This script generated a /etc/msmtprc based on env vars.
# Any valid msmtp config param name that is prefixed with MSMTP_ can be supplied as env var

# A list of all possible msmtp configuration params
# based on
# https://marlam.de/msmtp/msmtp.html#General-commands
# https://marlam.de/msmtp/msmtp.html#Authentication-commands
# https://marlam.de/msmtp/msmtp.html#TLS-commands
# https://marlam.de/msmtp/msmtp.html#Commands-specific-to-sendmail-mode
VALID_MSMTP_CONFIG_PARAMS=(host port source_ip proxy_host proxy_port socket timeout protocol domain auth user password passwordeval ntlmdomain tls tls_starttls tls_trust_file tls_crl_file tls_fingerprint tls_key_file tls_cert_file tls_certcheck tls_priorities tls_host_override tls_min_dh_prime_bits from allow_from_override dsn_notify dsn_return set_from_header set_date_header set_msgid_header remove_bcc_headers undisclosed_recipients logfile logfile_time_format aliases auto_from maildomain)
SECRET_PARAMS=(password)
ENV_VAR_PREFIX=MSMTP_
TARGET_FILE=/etc/msmtprc

config_file_content=$(
    cat <<EOF
# This msmtp-config (/etc/msmtprc) file is generated by the DZD REDCap docker (https://github.com/DZD-eV-Diabetes-Research/redcap-docker) start scripts.
# if you change anything here it will be overwriten on next container boot
defaults
tls on

account redcapmail
EOF
)
config_file_content="${config_file_content}\n"
for config_param_name in ${VALID_MSMTP_CONFIG_PARAMS[@]}; do
    env_var_name="${ENV_VAR_PREFIX}${config_param_name}"
    env_var_val=${!env_var_name}

    if [ ! -z "${env_var_val}" ]; then
        # Log if we set anything but do not output secrets to log
        if [[ ${SECRET_PARAMS[@]} =~ $config_param_name ]]; then
            echo "Set msmtp variable: $config_param_name ****"
        else
            echo "Set msmtp variable: $config_param_name $env_var_val"
        fi
        config_file_content="${config_file_content}${config_param_name} \"${env_var_val}\"\n"
    fi
done
config_file_content="${config_file_content}account default : redcapmail\n"
#$config_file_content=$(echo -e $config_file_content)

echo -e "$config_file_content" >${TARGET_FILE}
chown www-data:www-data ${TARGET_FILE}
chmod 600 ${TARGET_FILE}
