#!/bin/bash
# Script Version: 0.10
# Description: Check if Postfix is installed before proceeding with installation

# Validate hostname before proceeding
if [ "$(hostname)" == "$(hostname --fqdn)" ]; then
    echo "Error: Hostname and fully qualified domain name must differ."
    exit 1
fi

# Variables
# ========
POSTFIX_MAIN_CF=/etc/postfix/main.cf
SASL_PASSWD_FILE=/etc/postfix/sasl_passwd
SMTP_SERVER="mail.bubuit.net"
SMTP_PORT="587"
SMTP_USER="user"
SMTP_PASS="password"
RECIPIENT="root@mail.box"
TEST_RECIPIENT="root"
MAILNAME=$(hostname --fqdn)
ALIASES_FILE="/etc/aliases"

# Check if Postfix is already installed
if dpkg -l | grep -q "^ii  postfix "; then
    echo "Postfix is already installed. Skipping installation."
else
    # Preconfigure Postfix installation
    debconf-set-selections <<< "postfix postfix/mailname string $MAILNAME"
    debconf-set-selections <<< "postfix postfix/main_mailer_type string 'Local only'"

    # Install required packages non-interactively
    apt update
    apt install -y postfix libsasl2-modules mailutils
fi

# Configure Postfix for SMTP relay (only necessary changes)
postconf -e "relayhost = $SMTP_SERVER:$SMTP_PORT"
postconf -e "smtp_tls_security_level = may"
postconf -e "smtp_sasl_auth_enable = yes"
postconf -e "smtp_sasl_password_maps = hash:$SASL_PASSWD_FILE"
postconf -e "smtp_sasl_security_options = noanonymous"

# Store SMTP credentials
printf "$SMTP_SERVER:$SMTP_PORT $SMTP_USER:$SMTP_PASS\n" > $SASL_PASSWD_FILE
chmod 600 $SASL_PASSWD_FILE
postmap $SASL_PASSWD_FILE

# Update /etc/aliases
if [ -n "$RECIPIENT" ] && ! grep -q "^root: " $ALIASES_FILE; then
    echo "root: $RECIPIENT" >> $ALIASES_FILE
    newaliases
else
    echo "Alias for root already exists, skipping update."
fi
newaliases

# Reloading Postfix configuration
systemctl reload postfix

# Test email sending
echo "Test email from Postfix SMTP relay" | mail -s "Test Subject" root

# Verify logs
# Check mail logs using: tail -f /var/log/mail.log

# Postfix setup and test email completed