Add Gerrit email account and send-email configuration

We'll have to store Gerrit's email credentials in plain text. Protecting
from outside connections using these in case they'd ever leak is tricky.
We match the account `gerrit@...` in `user.access` and then the local IP
address of the gerrit container in `gerrit-client.access`, only allowing
authenticated users (`permit_sasl_authenticated`) from this IP.

Alternatively, we could use `permit` which would allow the whole gerrit
container to send emails from `gerrit@...` without login. Then the setup
would also allow more efficient, plain-text communication between Gerrit
and Postfix. The password would still be needed to login to IMAP (assu-
ming no further, invasive changes).
diff --git a/mail/config/user-patches.sh b/mail/config/user-patches.sh
index 4be7d15..5a10bbd 100644
--- a/mail/config/user-patches.sh
+++ b/mail/config/user-patches.sh
@@ -2,6 +2,46 @@
 
 set -e
 
+# Add local containers as trusted for postfix relaying.
+add_mynetworks_hosts() {
+    myhosts=
+    for host in mailserver "$@"; do
+        IP=$(host ${host} | sed -n 's/.*has address //p')
+        myhosts="${myhosts} ${IP}/32"
+    done
+    postconf "mynetworks =${myhosts}"
+}
+
+# Create given users, requiring a plain-text password in `/tmp/passwd/`.
+add_users_with_passwd() {
+    for user in "$@"; do
+        i=0
+        while [ -z "$(cat /tmp/passwd/${user}/secret 2>/dev/null)" ]; do
+            if [ ${i} -eq 10 ]; then
+                echo "ERROR: No password file for '${user}' after ${i}s."
+                exit 1
+            fi
+            sleep 1
+            i=$((i+1))
+        done
+
+        if [ ! -d /var/mail/${HOSTNAME#mail.}/${user} ]; then
+            setup email add gerrit@${HOSTNAME#mail.} $(cat /tmp/passwd/${user}/secret)
+        else
+            setup email update gerrit@${HOSTNAME#mail.} $(cat /tmp/passwd/${user}/secret)
+        fi
+    done
+}
+
 {
-	setup email list | grep -q '^\* gerrit@' || setup email add gerrit@${HOSTNAME#mail.} psst,gerrit
+    add_users_with_passwd gerrit
+
+    # Restrict gerrit@ sending to local IP:
+    if ! grep -q gerrit /tmp/docker-mailserver/user.access 2>/dev/null; then
+        echo "gerrit@${HOSTNAME#mail.} gerrit_sender_check" >>/tmp/docker-mailserver/user.access
+        postmap /tmp/docker-mailserver/user.access
+    fi
+    IP=$(host gerrit | sed -n 's/.*has address //p')
+    echo "${IP} permit_sasl_authenticated"  >/tmp/docker-mailserver/gerrit-client.access
+    postmap /tmp/docker-mailserver/gerrit-client.access
 }