#!/bin/bash
#wget -O- http://its.alexunderboots.ru/_deploy/i99-postfix.sh | bash /dev/stdin
# https://t.me/srv_admin/3662

apt update && apt install -y postfix mailutils libsasl2-modules postfix-pcre

myhostname=$(hostname --fqdn)
mysmtpserver='mx.alexunderboots.ru'
mysmtpport='465'
mymail='node@alexunderboots.ru'
mypass=$(echo 'YXc5NjU2Cg==' | base64 -d)

tmp='smtpd_banner = '${myhostname}' ESMTP $mail_name (Debian/GNU)'
yes | cp -i /etc/postfix/main.cf /root/main.cf.0
cat > /etc/postfix/main.cf << EOF
# See /usr/share/postfix/main.cf.dist for a commented, more complete version
${tmp}
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

alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
mynetworks = 127.0.0.0/8
inet_interfaces = loopback-only
recipient_delimiter = +

compatibility_level = 2

relayhost = ${mysmtpserver}:${mysmtpport}
smtp_use_tls = yes
smtp_tls_wrappermode = yes
smtp_tls_security_level = encrypt
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_tls_CApath = /etc/ssl/certs
smtp_sasl_security_options = noanonymous
smtp_sasl_tls_security_options = noanonymous
smtp_header_checks = pcre:/etc/postfix/smtp_header_checks
sender_canonical_maps =  regexp:/etc/postfix/sender_canonical_maps
EOF

yes | cp -i /etc/postfix/sasl_passwd /root/sasl_passwd.0
cat > /etc/postfix/sasl_passwd << EOF
${mysmtpserver} ${mymail}:${mypass}
EOF
postmap /etc/postfix/sasl_passwd

#tmp='/^from:.*/ REPLACE from: '$myhostname' <565110@565110.ru>'
tmp='/^from:.*/ REPLACE from: '
yes | cp -i /etc/postfix/smtp_header_checks /root/smtp_header_checks.0
cat > /etc/postfix/smtp_header_checks << EOF
${tmp} $myhostname <${mymail}>
EOF

tmp='/.+/    '
yes | cp -i /etc/postfix/sender_canonical_maps /root/sender_canonical_maps.0
cat > /etc/postfix/sender_canonical_maps << EOF
${tmp} ${mymail}
EOF

chown root:root /etc/postfix/sasl_passwd /etc/postfix/sasl_passwd.db
chmod 0600 /etc/postfix/sasl_passwd /etc/postfix/sasl_passwd.db
postfix reload

yes | cp -i /etc/aliases /root/aliases.0
cat >> /etc/aliases << EOF
root: ${mymail}
EOF
newaliases

systemctl enable --now postfix

echo "Test mail from postfix" | mail -s "Test from shell Postfix" ${mymail}
echo "Hello world from Proxmox" | /usr/bin/proxmox-mail-forward
