#!/bin/bash

set -e

host=$(relation-get host)
port=$(relation-get port)
connection_security=$(relation-get connection-security)
auth_method=$(relation-get auth-method)

declare -A ENV
case "$connection_security" in
    "none")
        secure="false"
        ;;
    "starttls")
        secure="true"
        ENV[SMTP_TLS_ENABLED]="true"
        ;;
    "ssl/tls")
        secure="true"
        ENV[SMTP_SECURE]="true"
        ENV[SMTP_TLS_ENABLED]="true"
        ;;
    *)
        error "Unsupported connection security: $connection_security"
        exit 1
        ;;
esac
case "$auth_method" in
    "none")
        :
        ;;
    "password")
        login=$(relation-get login) || true
        password=$(relation-get password) || true
        ENV[SMTP_USER]="$login"
        ENV[SMTP_PWD]="$password"
        ;;
    *)
        error "Unsupported auth method: $auth_method"
        exit 1
        ;;
esac


config-add "\
services:
  $MASTER_BASE_SERVICE_NAME:
    environment:
      SMTP_HOST: \"$host\"
      SMTP_PORT: \"$port\"
$(for key in "${!ENV[@]}"; do echo "      $key: \"${ENV[$key]//\$/\$\$}\""; done)
"