#!/bin/bash -e

# Apply previous SMTP options given in the packager wizard to the settings within
# the database. This will override existing settings.
# The user can just choose `skip` during `reconfigure` if they do not want that.

SMTP_CONFIG_FILE=/etc/${APP_NAME}/conf.d/smtp

if [ -f "$SMTP_CONFIG_FILE" ]; then
  source $SMTP_CONFIG_FILE
fi

if [ "$EMAIL_DELIVERY_METHOD" = "smtp" ]; then
  ${CLI} run rake "setting:set_to_env[\
email_delivery_method=EMAIL_DELIVERY_METHOD,\
smtp_authentication=SMTP_AUTHENTICATION,\
smtp_address=SMTP_HOST,\
smtp_port=SMTP_PORT,\
smtp_user_name=SMTP_USERNAME,\
smtp_password=SMTP_PASSWORD,\
smtp_domain=SMTP_DOMAIN\
]"
elif [ "$EMAIL_DELIVERY_METHOD" = "sendmail" ]; then
  ${CLI} run rake "setting:set_to_env[email_delivery_method=EMAIL_DELIVERY_METHOD]"
fi

# We have transferred all the SMTP options to their settings within the database.
# Next we remove them from the env. This way they don't pin the settings to the
# env values allowing users to still change the SMTP options at runtime.

# This only removes env vars generated by packager.
# If an admin still wants to pin a certain setting to a given value they can still do
# so by using the prefixed setting names. For instance:
#
#  openproject config:set OPENPROJECT_SMTP__PORT=42

${CLI} config:unset EMAIL_DELIVERY_METHOD
${CLI} config:unset SMTP_AUTHENTICATION
${CLI} config:unset SMTP_HOST
${CLI} config:unset SMTP_PORT
${CLI} config:unset SMTP_USERNAME
${CLI} config:unset SMTP_PASSWORD
${CLI} config:unset SMTP_DOMAIN

# Same for default language
${CLI} config:unset OPENPROJECT_DEFAULT_LANGUAGE
