#!/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

# wait for mailman3 to come back after restart
sleep 15

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)"

# Give the service more time to start.
for _ in {1..10}; do 
    sleep 5

    curl -s --show-error --user "$admin_user:$admin_pass" http://localhost:$port/3.1/system/versions 2>&1 && exit 0
done
exit 1
