#!/bin/sh -eu

. alterator-postfix-dovecot-functions

TEMPLATES_DIR=/usr/share/alterator-postfix-dovecot

if [ -z "${new_server_role:-}" ]; then
    old_server_role=""
    new_server_role="$(shell_config_get /etc/sysconfig/system SERVER_ROLE)"
fi

[ -n "$new_server_role" -a "$new_server_role" != "$old_server_role" ] || exit 0
[ "$new_server_role" = "master" ] || exit 0

cp -Rb --suffix='.bak' "$TEMPLATES_DIR"/* /etc/
if postconf_read mynetworks | grep -qs '127\.0\.0\.1'; then
    postconf_read mynetworks > "$MYNETWORKS"
fi
echo "@domain@" > "$MYDESTINATION"

# Init postfix config
postconf_write smtpd_use_tls yes
postconf_write smtpd_tls_auth_only yes
postconf_write smtpd_tls_received_header yes
postconf_write smtpd_tls_key_file "/var/lib/ssl/private/postfix.key"
postconf_write smtpd_tls_cert_file "/var/lib/ssl/certs/postfix.cert"

postconf_write smtpd_sasl_auth_enable yes
postconf_write smtpd_sasl_tls_security_options 'noanonymous'
postconf_write smtpd_sasl_security_options 'noanonymous, noplaintext'

postconf_write mynetworks 'localhost, $myhostname, $config_directory/mynetworks'
#    postconf_write mynetworks '$config_directory/mynetworks'
postconf_write smtpd_helo_restrictions 'check_recipient_access cdb:/etc/postfix/whitelist, permit_mynetworks, permit_sasl_authenticated, check_helo_access cdb:/etc/postfix/helo_access, permit'
postconf_write smtpd_client_restrictions 'check_recipient_access cdb:/etc/postfix/whitelist, permit_mynetworks, permit_sasl_authenticated, check_client_access cdb:/etc/postfix/client_access, permit'
postconf_write smtpd_sender_restrictions 'check_recipient_access cdb:/etc/postfix/whitelist, permit_mynetworks, permit_sasl_authenticated, check_sender_access cdb:/etc/postfix/sender_access, permit'
postconf_write smtpd_recipient_restrictions 'check_recipient_access cdb:/etc/postfix/recipient_access, permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination, permit'

postconf_write virtual_alias_maps 'ldap:/etc/postfix/ldap-aliases.cf, ldap:/etc/postfix/ldap-users.cf'
postconf_write local_recipient_maps 'proxy:unix:passwd.byname $alias_maps ldap:/etc/postfix/ldap-users.cf'
postconf_write smtpd_sasl_path private/auth
postconf_write smtpd_sasl_type dovecot
postconf_write mailbox_unpriv_delivery no
##
