#!/bin/bash

# install postfix
debconf-set-selections <<< "postfix postfix/mailname string localhost" 2>&1
debconf-set-selections <<< "postfix postfix/main_mailer_type string 'Internet Site'" 2>&1
hostname localhost
apt-get install -y postfix 2>&1

# restart mailman3 after postfix is available
service mailman3 restart

mailman3_cfg="/etc/mailman3/mailman.cfg"

port="$(sed -ne 's|^port:\s*\(\S\+\)|\1|p' $mailman3_cfg)"
admin_user="$(sed -ne 's|^admin_user:\s*\(\S\+\)|\1|p' $mailman3_cfg)"
admin_pass="$(sed -ne 's|^admin_pass:\s*\(\S\+\)|\1|p' $mailman3_cfg)"

# Poll instead of a fixed sleep: startup time varies (see #1051957).
# Transient connection errors are expected while it comes up, so keep
# them off stderr and only surface the last one if it never does.
err_file="$(mktemp)"
trap 'rm -f "$err_file"' EXIT

url="http://localhost:$port/3.1/system/versions"
for i in $(seq 1 30); do
    if response="$(curl -s --fail --user "$admin_user:$admin_pass" "$url" 2>"$err_file")"; then
        echo "$response"
        exit 0
    fi
    sleep 1
done

echo "mailman3 REST API did not come up within 30s" >&2
cat "$err_file" >&2
exit 1
