#!/bin/bash

#submission master.cf
sudo postconf -M submission/inet='submission inet n       -       y      -       -       smtpd'
sudo postconf -P submission/inet/syslog_name=postfix/submission
sudo postconf -P submission/inet/smtpd_tls_security_level=encrypt
sudo postconf -P submission/inet/smtpd_sasl_auth_enable=yes
sudo postconf -P submission/inet/smtpd_sasl_type=dovecot
sudo postconf -P submission/inet/smtpd_sasl_path=private/auth
sudo postconf -P submission/inet/smtpd_reject_unlisted_recipient=no
sudo postconf -P submission/inet/smtpd_client_restrictions=permit_sasl_authenticated,reject
sudo postconf -P submission/inet/milter_macro_daemon_name=ORIGINATING


#smtps master.cf
sudo postconf -M smtps/inet='smtps     inet  n       -       -       -       -       smtpd'
sudo postconf -P smtps/inet/syslog_name=postfix/smtps
sudo postconf -P smtps/inet/smtpd_tls_wrappermode=yes
sudo postconf -P smtps/inet/smtpd_sasl_auth_enable=yes
sudo postconf -P smtps/inet/smtpd_sasl_type=dovecot
sudo postconf -P smtps/inet/smtpd_sasl_path=private/auth
sudo postconf -P smtps/inet/smtpd_client_restrictions=permit_sasl_authenticated,reject
sudo postconf -P smtps/inet/milter_macro_daemon_name=ORIGINATING

#SPF master.cf
sudo postconf -M policy-spf/unix='policy-spf  unix  -       n       n       -       -       spawn       user=nobody argv=/usr/bin/policyd-spf'

sudo printf "%s\n" "user = dbUserReplace" "password = dbPasswordReplace" "hosts = 127.0.0.1" "dbname = dbNmeReplace" "query = SELECT destination FROM virtual_aliases WHERE source='%s'" > /etc/postfix/mysql-virtual-alias-maps.cf
sudo printf "%s\n" "user = dbUserReplace" "password = dbPasswordReplace" "hosts = 127.0.0.1" "dbname = dbNmeReplace" "query = SELECT destination FROM virtual_aliases WHERE source='%s'" > /etc/postfix/mysql-virtual-email2email.cf
sudo printf "%s\n" "user = dbUserReplace" "password = dbPasswordReplace" "hosts = 127.0.0.1" "dbname = dbNmeReplace" "query = SELECT 1 FROM virtual_domains WHERE name='%s'" > /etc/postfix/mysql-virtual-mailbox-domains.cf
sudo printf "%s\n" "user = dbUserReplace" "password = dbPasswordReplace" "hosts = 127.0.0.1" "dbname = dbNmeReplace" "query = SELECT 1 FROM virtual_users WHERE email='%s'" > /etc/postfix/mysql-virtual-mailbox-maps.cf

sudo printf "%s\n" "/^Content-Type:/i PREPEND List-Unsubscribe: <mailto:unsubscribe@domainReplace>" > /etc/postfix/list_unsub_header

#main.cf full replace
main_cf="$(cat <<-EOF
# See /usr/share/postfix/main.cf.dist for a commented, more complete version

# Debian specific:  Specifying a file name will cause the first
# line of that file to be used as the name.  The Debian default
# is /etc/mailname.
#myorigin = /etc/mailname

smtpd_banner = $myhostname ESMTP $mail_name (Ubuntu)
biff = no

# appending .domain is the MUA's job.
append_dot_mydomain = no

# Uncomment the next line to generate "delayed mail" warnings
#delay_warning_time = 4h

readme_directory = no

# See http://www.postfix.org/COMPATIBILITY_README.html -- default to 2 on
# fresh installs.
compatibility_level = 2

# TLS parameters
#smtpd_tls_cert_file=/etc/letsencrypt/live/domainReplace/fullchain.pem
#smtpd_tls_key_file=/etc/letsencrypt/live/domainReplace/privkey.pem

smtpd_tls_cert_file = /etc/letsencrypt/live/domainReplace/cert.pem
smtpd_tls_key_file = /etc/letsencrypt/live/domainReplace/privkey.pem
smtpd_tls_CAfile = /etc/letsencrypt/live/domainReplace/fullchain.pem

smtpd_use_tls=yes
smtpd_tls_auth_only = yes
smtp_tls_security_level = may
smtpd_tls_security_level = may
smtpd_sasl_security_options = noanonymous, noplaintext
smtpd_sasl_tls_security_options = noanonymous

# Authentication
smtpd_sasl_type = dovecot
smtpd_sasl_path = private/auth
smtpd_sasl_auth_enable = yes
strict_mailbox_ownership = no
# See /usr/share/doc/postfix/TLS_README.gz in the postfix-doc package for
# information on enabling SSL in the smtp client.

# Restrictions
smtpd_helo_restrictions =
        permit_mynetworks,
        permit_sasl_authenticated,
        reject_invalid_helo_hostname,
        reject_non_fqdn_helo_hostname
smtpd_recipient_restrictions =
        permit_mynetworks,
        permit_sasl_authenticated,
        reject_non_fqdn_recipient,
        reject_unknown_recipient_domain,
        reject_unlisted_recipient,
        reject_unauth_destination,
        check_policy_service unix:private/policy-spf
smtpd_sender_restrictions =
        permit_mynetworks,
        permit_sasl_authenticated,
        reject_non_fqdn_sender,
        reject_unknown_sender_domain
smtpd_relay_restrictions =
        permit_mynetworks,
        permit_sasl_authenticated,
        defer_unauth_destination

# See /usr/share/doc/postfix/TLS_README.gz in the postfix-doc package for
# information on enabling SSL in the smtp client.

myhostname = domainReplace
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
mydomain = domainReplace
myorigin = \$mydomain
mydestination = localhost
relayhost =
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = all
inet_protocols = ipv4
#inet_protocols = all

# Handing off local delivery to Dovecot's LMTP, and telling it where to store mail
virtual_transport = lmtp:unix:private/dovecot-lmtp

# Virtual domains, users, and aliases
virtual_mailbox_domains = mysql:/etc/postfix/mysql-virtual-mailbox-domains.cf
virtual_mailbox_maps = mysql:/etc/postfix/mysql-virtual-mailbox-maps.cf
virtual_alias_maps = mysql:/etc/postfix/mysql-virtual-alias-maps.cf,
        mysql:/etc/postfix/mysql-virtual-email2email.cf

# Even more Restrictions and MTA params
disable_vrfy_command = yes
strict_rfc821_envelopes = yes
#smtpd_etrn_restrictions = reject
#smtpd_reject_unlisted_sender = yes
#smtpd_reject_unlisted_recipient = yes
smtpd_delay_reject = yes
smtpd_helo_required = yes
smtp_always_send_ehlo = yes
#smtpd_hard_error_limit = 1
smtpd_timeout = 30s
smtp_helo_timeout = 15s
smtp_rcpt_timeout = 15s
smtpd_recipient_limit = 40
minimal_backoff_time = 180s
maximal_backoff_time = 3h

# Reply Rejection Codes
invalid_hostname_reject_code = 550
non_fqdn_reject_code = 550
unknown_address_reject_code = 550
unknown_client_reject_code = 550
unknown_hostname_reject_code = 550
unverified_recipient_reject_code = 550
unverified_sender_reject_code = 550
header_checks = regexp:/etc/postfix/list_unsub_header


# SPF
policy-spf_time_limit = 3600s

# DKIM
milter_protocol = 6
milter_default_action = accept
#smtpd_milters = inet:localhost:10001,inet:localhost:8891,local:opendmarc/opendmarc.sock
smtpd_milters =  inet:localhost:8891,local:opendmarc/opendmarc.sock
non_smtpd_milters = inet:localhost:8891

#postsrd
sender_canonical_maps = tcp:localhost:10001
sender_canonical_classes = envelope_sender
recipient_canonical_maps = tcp:localhost:10002
recipient_canonical_classes= envelope_recipient,header_recipient

EOF
)"

sudo echo "$main_cf" > /etc/postfix/main.cf


sudo chmod -R o-rwx /etc/postfix

#################################DMARK#################################
sudo systemctl enable opendmarc

#remove all the lines what start with
sudo sed -i '/^AuthservID \|^TrustedAuthservIDs \|^RejectFailures \|^RequiredHeaders \|^SPFSelfValidate \|^IgnoreAuthenticatedClients\|^UserID\|^Socket local/d' /etc/opendmarc.conf
#at the end of file add new lines
sudo sed -i '15i\
AuthservID OpenDMARC\
TrustedAuthservIDs mail.domainReplace\
RejectFailures true\
RequiredHeaders true\
SPFSelfValidate true\
IgnoreAuthenticatedClients true\
UserID opendmarc\
Socket local:/var/spool/postfix/opendmarc/opendmarc.sock' /etc/opendmarc.conf

sudo adduser postfix opendmarc
sudo mkdir -p /var/spool/postfix/opendmarc
sudo chown opendmarc:opendmarc /var/spool/postfix/opendmarc -R
sudo chmod 750 /var/spool/postfix/opendmarc/ -R

sudo systemctl restart opendmarc

#################################OpenDKIM#################################

sudo opendkim-genkey -t -s mail -d domainReplace
sudo cp mail.private /etc/postfix/dkim.key

#remove all the lines what start with
sudo sed -i '/^UserID\|^UMask\|^Domain\|^KeyFile\|^Selector\|^Socket\|^SOCKET\|^AutoRestart\|^AutoRestartRate\|^LogWhy\|^SyslogSuccess\|^LogResults\|^Canonicalization\|^Mode/d' /etc/opendkim.conf

#at the end of file add new lines
sudo sed -i '$a\
UMask			        007\
Socket			        local:/run/opendkim/opendkim.sock\
UserID                  opendkim\
Domain                  domainReplace\
SOCKET                  inet:8891@localhost\
AutoRestart             Yes\
AutoRestartRate         10/1h\
LogWhy                  Yes\
SyslogSuccess           Yes\
LogResults              Yes\
Canonicalization        relaxed/simple\
Mode                    sv\
Selector                mail\
KeyFile                 /etc/postfix/dkim.key' /etc/opendkim.conf

sudo adduser postfix opendkim
sudo systemctl restart postfix opendmarc opendkim

#################################POSTSRSD#################################
#remove all the lines what start with
sudo sed -i '/^SRS_DOMAIN\|^SRS_SEPARATOR/d' /etc/default/postsrsd

#at the end of file add new lines
sudo sed -i '8i\
SRS_DOMAIN=domainReplace\
SRS_SEPARATOR=+' /etc/default/postsrsd

sudo systemctl restart postsrsd postfix
