#!/bin/bash

# shellcheck source=../scripts/helpers/index.sh
source /usr/local/bin/helpers/index.sh

function _main() {
  _require_n_parameters_or_print_usage 2 "${@}"

  local DOMAIN="${1}"
  local RELAY_ACCOUNT="${2}"
  local PASSWD="${3}"

  _validate_parameters
  _add_relayhost_credentials
}

function __usage() {
  printf '%s' "${PURPLE}addsaslpassword${RED}(${YELLOW}8${RED})

${ORANGE}USAGE${RESET}
    ./setup.sh relay add-auth <SENDER DOMAIN> <RELAY ACCOUNT> [<RELAY PASSWORD>]

${ORANGE}OPTIONS${RESET}
    ${BLUE}Generic Program Information${RESET}
        help       Print the usage information.

${ORANGE}DESCRIPTION${RESET}
    Add credentials to authenticate to a relay-host service.

    To avoid a password being logged in the command history of your shell,
    you may omit it, you'll be prompted to input the password instead.

${ORANGE}EXAMPLES${RESET}
    ${LWHITE}./setup.sh relay add-auth example.com relay-account${RESET}
        Any mail submitted for your '@example.com' accounts that is sent
        through a relay-host service will authenticate with the credentials:
        'relay-account' + the password you entered at the prompt.

${ORANGE}EXIT STATUS${RESET}
    Exit status is 0 if command was successful. If wrong arguments are provided
    or arguments contain errors, the script will exit early with exit status 1.

"
}

function _validate_parameters() {
  [[ -z ${DOMAIN}        ]] && { __usage ; _exit_with_error 'No domain specified'        ; }
  [[ -z ${RELAY_ACCOUNT} ]] && { __usage ; _exit_with_error 'No relay account specified' ; }
  _password_request_if_missing
}

# Config is for sender dependent relay-host auth,
# current support restricts senders to their domain scope.
#
# NOTE: This command does not support providing a relay-host
# as the lookup key, it only supports a lookup via sender domain.
function _add_relayhost_credentials() {
  local SENDER="@${DOMAIN}"
  local RELAY_HOST_ENTRY_AUTH="${RELAY_ACCOUNT}:${PASSWD}"
  local DATABASE_PASSWD='/tmp/docker-mailserver/postfix-sasl-password.cf'

  _db_entry_add_or_replace "${DATABASE_PASSWD}" "${SENDER}" "${RELAY_HOST_ENTRY_AUTH}"
}

_main "${@}"
