#!/bin/bash
set -e

echo "=== receiver-mta: starting services ==="

# Fix DNS resolution: ensure Postfix and milters can do DNS lookups via BIND9
echo "nameserver 10.0.0.2" > /etc/resolv.conf

# Add policyd-spf entry to master.cf
if ! grep -q "policyd-spf" /etc/postfix/master.cf; then
    echo "" >> /etc/postfix/master.cf
    echo "# SPF policy daemon" >> /etc/postfix/master.cf
    echo "policyd-spf  unix  -       n       n       -       0       spawn" >> /etc/postfix/master.cf
    echo "    user=policyd-spf argv=/usr/bin/policyd-spf" >> /etc/postfix/master.cf
    echo "[*] Added policyd-spf to master.cf"
fi

# Start rsyslog for mail logging
rsyslogd

# Start OpenDKIM (verify)
echo "[*] Starting OpenDKIM (verify mode) ..."
opendkim -x /etc/opendkim.conf
sleep 1

# Start OpenDMARC
echo "[*] Starting OpenDMARC ..."
opendmarc -c /etc/opendmarc.conf
sleep 1

# Start Postfix
echo "[*] Starting Postfix ..."
postfix start

echo "[✓] receiver-mta ready  (mail.receiver.lab / 10.0.0.20)"

# Keep container alive and tail the log
tail -F /var/log/mail.log 2>/dev/null
