# Its own mail account in the Core's LDAP, for sending only, with the
# password from .env. Not a person (objectClass account, not
# inetOrgPerson), so it can't sign in to Authelia, Nextcloud or Superpanel;
# the mail server checks its password with LDAP. mailEnabled FALSE: no
# mailbox. Its address, coreapp-{{NAME}}@<domain>, is its own, so a
# person's mail login never finds two entries. Safe to run again.
LDAP_BASE="$(sed -n 's/^LDAP_SEARCH_BASE=ou=people,//p' /federated/apps/mail/.env)"
LDAP_ADMIN_PW="$(cat /federated/apps/ldap/.ldap.secret)"
MAIL_DN="uid=coreapp-{{NAME}},ou=people,$LDAP_BASE"
SMTP_PASSWORD="$(sed -n 's/^SMTP_PASSWORD=//p' /federated/apps/{{NAME}}/.env)"
# Entries with its uid or address: none, or only its own
MAIL_FOUND="$(docker exec ldap ldapsearch -LLL -o ldif-wrap=no -x -H ldap://localhost \
  -D "cn=admin,$LDAP_BASE" -w "$LDAP_ADMIN_PW" -b "$LDAP_BASE" \
  "(|(uid=coreapp-{{NAME}})(mail=coreapp-{{NAME}}@$DOMAIN))" dn description)"
if [ -z "$MAIL_FOUND" ]; then
  docker exec -i ldap ldapadd -x -H ldap://localhost -D "cn=admin,$LDAP_BASE" -w "$LDAP_ADMIN_PW" \
    > /dev/null <<LDIF
dn: $MAIL_DN
objectClass: account
objectClass: simpleSecurityObject
objectClass: PostfixBookMailAccount
uid: coreapp-{{NAME}}
description: coreapps: {{NAME}}
mail: coreapp-{{NAME}}@$DOMAIN
mailEnabled: FALSE
userPassword: {CRYPT}!
LDIF
  MAIL_FOUND="dn: $MAIL_DN
description: coreapps: {{NAME}}"
fi
if [ "$MAIL_FOUND" = "dn: $MAIL_DN
description: coreapps: {{NAME}}" ]; then
  # The password, on stdin; the server hashes it
  printf '%s' "$SMTP_PASSWORD" | docker exec -i ldap ldappasswd -x -H ldap://localhost \
    -D "cn=admin,$LDAP_BASE" -w "$LDAP_ADMIN_PW" -T /dev/stdin "$MAIL_DN"
else
  echo "LDAP already has an entry with uid coreapp-{{NAME}} or its address that isn't this app's mail account; left it alone, so the app can't send mail." >&2
fi
unset LDAP_BASE LDAP_ADMIN_PW MAIL_DN SMTP_PASSWORD MAIL_FOUND
