#!/bin/bash

# Function to get default IP address
get_default_ip() {
  ip addr show | awk '/inet/ && /brd/ {print $2}' | cut -d/ -f1 | head -n 1
}

# Prompt the user for inputs
read -p "Enter your domain: " DOMAIN
read -p "Enter your hostname (default: host.$DOMAIN): " HOSTNAME
HOSTNAME=${HOSTNAME:-host.$DOMAIN}
DEFAULT_IP=$(get_default_ip)
read -p "Enter your IP address (default: $DEFAULT_IP): " IP_ADDRESS
IP_ADDRESS=${IP_ADDRESS:-$DEFAULT_IP}
read -p "Enter your SMTP username: " USERNAME
read -s -p "Enter your SMTP password: " PASSWORD
echo

# Display the entered information
echo "Domain: $DOMAIN"
echo "Hostname: $HOSTNAME"
echo "IP Address: $IP_ADDRESS"
echo "SMTP Username: $USERNAME"

# Confirm the information
read -p "Is the above information correct? (y/n): " CONFIRM
if [[ $CONFIRM != "y" ]]; then
  echo "Aborting setup."
  exit 1
fi

# Save the details for later use
echo "DOMAIN=$DOMAIN" > smtp_details.conf
echo "HOSTNAME=$HOSTNAME" >> smtp_details.conf
echo "IP_ADDRESS=$IP_ADDRESS" >> smtp_details.conf
echo "USERNAME=$USERNAME" >> smtp_details.conf
echo "PASSWORD=$PASSWORD" >> smtp_details.conf

# Remove previous installations of sendmail, postfix, opendkim, libsasl2-modules, sasl2-bin, dovecot-core, opendmarc, bind9
echo "Removing previous installations of sendmail, postfix, opendkim, libsasl2-modules, sasl2-bin, dovecot-core, opendmarc, bind9..."

sudo apt-get remove --purge -y sendmail postfix opendkim libsasl2-modules sasl2-bin dovecot-core opendmarc bind9

# Remove residual configuration files
sudo rm -rf /etc/postfix /etc/dovecot /etc/opendkim /etc/default/saslauthd /etc/opendmarc /etc/bind

# Clean up
sudo apt-get autoremove -y
sudo apt-get autoclean

echo "Previous installations removed."

# Install necessary packages
echo "Installing Postfix, Cyrus SASL, OpenDKIM, OpenDMARC, BIND9, and dependencies..."

sudo apt-get update
sudo apt-get install -y postfix libsasl2-2 sasl2-bin libsasl2-modules db-util procmail opendkim opendkim-tools opendmarc bind9 bind9utils bind9-doc

echo "Packages installed."

echo "Configuring OpenDkim"

# Configure OpenDKIM
echo "Configuring OpenDKIM..."

sudo tee /etc/opendkim.conf > /dev/null <<EOL
Syslog                  yes
UMask                   002
Canonicalization        relaxed/simple
Mode                    sv
SubDomains              no
AutoRestart             yes
AutoRestartRate         10/1h
Background              yes
DNSTimeout              5
SignatureAlgorithm      rsa-sha256

KeyTable                refile:/etc/opendkim/key.table
SigningTable            refile:/etc/opendkim/signing.table
ExternalIgnoreList      refile:/etc/opendkim/trusted.hosts
InternalHosts           refile:/etc/opendkim/trusted.hosts
Socket                  inet:8891@localhost
PidFile                 /var/run/opendkim/opendkim.pid
UserID                  opendkim:opendkim
EOL

sudo mkdir -p /etc/opendkim/keys

# Generate DKIM keys
sudo opendkim-genkey -s mail -d $DOMAIN -D /etc/opendkim/keys

# Set appropriate permissions for the keys
sudo chown -R opendkim:opendkim /etc/opendkim/keys

# Configure OpenDKIM key and signing tables
echo "Configuring OpenDKIM key and signing tables..."

sudo tee /etc/opendkim/key.table > /dev/null <<EOL
mail._domainkey.$DOMAIN $DOMAIN:mail:/etc/opendkim/keys/mail.private
EOL

sudo tee /etc/opendkim/signing.table > /dev/null <<EOL
*@${DOMAIN} mail._domainkey.${DOMAIN}
EOL

sudo tee /etc/opendkim/trusted.hosts > /dev/null <<EOL
127.0.0.1
localhost
${IP_ADDRESS}
${DOMAIN}
EOL

# Reload OpenDKIM
echo "Reloading OpenDKIM..."

sudo systemctl restart opendkim
sudo systemctl enable opendkim

# Configure OpenDMARC
echo "Configuring OpenDMARC..."

sudo tee /etc/opendmarc.conf > /dev/null <<EOL
AuthservID          OpenDMARC
PidFile             /var/run/opendmarc/opendmarc.pid
Socket              inet:8893@localhost
Syslog              true
TrustedAuthservIDs  ${DOMAIN}
IgnoreHosts         /etc/opendmarc/ignore.hosts
EOL

sudo mkdir -p /etc/opendmarc
sudo tee /etc/opendmarc/ignore.hosts > /dev/null <<EOL
127.0.0.1
localhost
${DOMAIN}
EOL

# Backup and configure Postfix main.cf
echo "Configuring Postfix main.cf..."

sudo mv /etc/postfix/main.cf /etc/postfix/main.cf.bak

sudo tee /etc/postfix/main.cf > /dev/null <<EOL
inet_interfaces = all
mynetworks = $IP_ADDRESS/32
mydestination =
smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination
smtpd_sasl_auth_enable = yes
broken_sasl_auth_clients = yes
header_checks = regexp:/etc/postfix/header_checks
smtpd_sasl_security_options = noanonymous
smtpd_client_restrictions = permit_mynetworks,permit_sasl_authenticated,reject
smtpd_sasl_authenticated_header = yes
smtpd_sender_restrictions = permit_mynetworks
smtpd_sasl_type = cyrus
smtpd_sasl_path = smtpd
inet_protocols = all
smtpd_tls_auth_only = no
smtpd_recipient_restrictions = permit_mynetworks,permit_sasl_authenticated,reject_unauth_destination
recipient_delimiter = +
smtpd_tls_security_level = may
smtpd_tls_loglevel = 1
smtpd_tls_received_header = yes
smtp_tls_note_starttls_offer = yes
smtpd_tls_session_cache_timeout = 3600s
smtpd_milters = inet:127.0.0.1:8891
non_smtpd_milters = $smtpd_milters 
milter_default_action = accept 
EOL

# Configure Postfix master.cf
echo "Configuring Postfix master.cf..."

sudo sed -i 's/^smtp      inet  n       -       y       -       -       smtpd/#&/' /etc/postfix/master.cf

sudo tee -a /etc/postfix/master.cf > /dev/null <<EOL
submission inet n       -       y       -       -       smtpd
  -o syslog_name=postfix/submission
  -o smtpd_tls_security_level=may
  -o smtpd_sasl_auth_enable=yes
  -o smtpd_reject_unlisted_recipient=no
  -o smtpd_recipient_restrictions=permit_sasl_authenticated,reject
  -o milter_macro_daemon_name=ORIGINATING
EOL

# Add SMTP authentication
echo "Configuring SMTP authentication..."

sudo mkdir -p /etc/postfix/sasl
sudo tee /etc/postfix/sasl/smtpd.conf > /dev/null <<EOL
pwcheck_method: saslauthd
mech_list: plain login
EOL

# Add header_checks
echo "Adding header checks..."

sudo tee /etc/postfix/header_checks > /dev/null <<EOL
/^Received:/ IGNORE
/^X-Originating-IP:/ IGNORE
/^X-Mailer:/ IGNORE
/^User-Agent:/ IGNORE
EOL

# Copy the configuration to the chroot directory
echo "Copying configuration to the chroot directory..."

sudo mkdir -p /var/spool/postfix/etc/postfix/sasl
sudo cp /etc/postfix/header_checks  /var/spool/postfix/etc/postfix/
sudo cp /etc/postfix/sasl/smtpd.conf /var/spool/postfix/etc/postfix/sasl/

# Reload Postfix configuration
echo "Reloading Postfix configuration..."

sudo postfix reload

# Ensure Postfix service is enabled and started
echo "Enabling and starting Postfix service..."

sudo systemctl enable postfix
sudo systemctl start postfix

# Configure saslauthd
echo "Configuring saslauthd..."

sudo tee /etc/default/saslauthd > /dev/null <<EOL
START=yes
MECHANISMS="pam"
OPTIONS="-c -m /var/spool/postfix/var/run/saslauthd"
EOL

# Create the required directories and set permissions
echo "Creating directories and setting permissions..."

sudo mkdir -p /var/spool/postfix/var/run/saslauthd
sudo chown -R postfix:postfix /var/spool/postfix/var/run/saslauthd
sudo chmod 750 /var/spool/postfix/var/run/saslauthd

# Reload and restart saslauthd service
echo "Reloading and restarting saslauthd service..."

sudo systemctl daemon-reload
sudo systemctl restart saslauthd
sudo systemctl enable saslauthd

# Add Postfix user to sasl group
echo "Adding Postfix user to sasl group..."

sudo usermod -a -G sasl postfix

# Adding a local user
echo "Adding a local user..."

sudo useradd $USERNAME
echo "$USERNAME:$PASSWORD" | sudo chpasswd

# Verify the user was added to saslauthd
sudo sasldblistusers2




# Reload OpenDMARC
echo "Reloading OpenDMARC..."

sudo systemctl restart opendmarc
sudo systemctl enable opendmarc

# BIND9 configuration
echo "Configuring BIND9..."

sudo tee /etc/bind/named.conf.local > /dev/null <<EOL
zone "${DOMAIN}" {
    type master;
    file "/etc/bind/db.${DOMAIN}";
};

zone "77.48.92.in-addr.arpa" {
    type master;
    file "/etc/bind/db.92.48.77";
};
EOL

extract_dkim_key() {
    local DKIM_KEY=$(cat /etc/opendkim/keys/mail.txt)
    echo $DKIM_KEY
}

# Create forward zone file
echo "Creating forward zone file..."

sudo tee /etc/bind/db.${DOMAIN} > /dev/null <<EOL
\$TTL 1d
@               IN      SOA     dns1.$DOMAIN. host.$DOMAIN. (
                1        ; serial
                6h       ; refresh after 6 hours
                1h       ; retry after 1 hour
                1w       ; expire after 1 week
                1d )     ; minimum TTL of 1 day
;
;
; Name Server Information
@               IN      NS      ns1.$DOMAIN.
@               IN      NS      ns2.$DOMAIN.
ns1             IN      A       $IP_ADDRESS
ns2             IN      A       $IP_ADDRESS

;
;
; Mail Server Information
$DOMAIN.           IN      MX      10      mail.$DOMAIN.
mail            IN      A       $IP_ADDRESS
;
;
; A records
host.$DOMAIN.        IN      A      $IP_ADDRESS
$DOMAIN.             IN      A      $IP_ADDRESS
; Additional A Records:
www             IN      A       $IP_ADDRESS
site            IN      A       $IP_ADDRESS
;
; TXT records
$(extract_dkim_key)
$DOMAIN.        IN     TXT       "v=spf1 a mx ip4:$IP_ADDRESS ~all"
_dmarc.$DOMAIN.  IN     TXT         "v=DMARC1; p=none; rua=mailto:dmarc-reports@$DOMAIN;"
;
; Additional CNAME Records:
slave           IN      CNAME   www.$DOMAIN.

EOL

# Create reverse zone file
echo "Creating reverse zone file..."

sudo tee /etc/bind/db.92.48.77 > /dev/null <<EOL
\$TTL    604800
@       IN      SOA     ns1.${DOMAIN}. admin.${DOMAIN}. (
                              2         ; Serial
                         604800         ; Refresh
                          86400         ; Retry
                        2419200         ; Expire
                         604800 )       ; Negative Cache TTL
;
@       IN      NS      ns1.${DOMAIN}.
@       IN      NS      ns2.${DOMAIN}.
53.77.48.92.in-addr.arpa. IN      PTR     ${DOMAIN}.
53.77.48.92.in-addr.arpa. IN      PTR     mail.${DOMAIN}.
53.77.48.92.in-addr.arpa. IN      PTR     ns1.${DOMAIN}.
53.77.48.92.in-addr.arpa. IN      PTR     ns2.${DOMAIN}.
EOL

# Restart BIND9
echo "Restarting BIND9 service..."

sudo systemctl restart named
sudo systemctl enable named

# Output generated keys and records
echo
echo "SMTP Username: ${USERNAME}"
echo "SMTP Password: ${PASSWORD}"
echo
echo "DKIM record:"
cat /etc/opendkim/keys/mail.txt
echo
echo "SPF record:"
echo "v=spf1 mx ip4:${IP_ADDRESS} -all"
echo
echo "DMARC record:"
echo "v=DMARC1; p=none; rua=mailto:dmarc-reports@${DOMAIN}; ruf=mailto:dmarc-reports@${DOMAIN}; sp=none; aspf=r; adkim=r"

echo "Setup completed."