#!/bin/bash

# Stop services
systemctl stop postfix dovecot mariadb amavisd spamassassin opendkim

# Disable services
systemctl disable postfix dovecot mariadb amavisd spamassassin opendkim

# Remove packages
dnf -y remove postfix postfix-mysql dovecot dovecot-mysql mariadb-server mariadb amavisd-new spamassassin opendkim

# Remove configuration files
rm -rf /etc/postfix
rm -rf /etc/dovecot
rm -rf /etc/my.cnf.d
rm -rf /etc/amavisd
rm -rf /etc/mail/spamassassin
rm -rf /etc/opendkim
rm -rf /var/lib/mysql

# Remove postfix directories if still exist
rm -rf /var/spool/postfix

# Remove virtual mailbox configuration files
rm -f /etc/postfix/virtual-mailbox-domains.conf
rm -f /etc/postfix/virtual-mailbox-users.conf
rm -f /etc/postfix/virtual-alias-maps.conf

# Remove additional postfix configurations added for Amavis, SpamAssassin, and OpenDKIM
sed -i '/^smtp-amavis /d' /etc/postfix/master.cf
sed -i '/^127.0.0.1:10025 /d' /etc/postfix/master.cf
sed -i '/^spamassassin /d' /etc/postfix/master.cf
sed -i '/^-o content_filter=spamassassin /d' /etc/postfix/master.cf
sed -i '/^# Milter configuration for DKIM/,/^non_smtpd_milters = /d' /etc/postfix/main.cf
sed -i '/^smtpd_recipient_restrictions = permit_mynetworks,check_sender_access /d' /etc/postfix/main.cf

# Remove Dovecot DH param certificate
rm -f /etc/dovecot/dh.pem

# Optionally, remove any Let's Encrypt certificates (be careful with this if you use them for other services)
# rm -rf /etc/letsencrypt/live/$myhostname

# Cleanup MariaDB repository
rm -f /etc/yum.repos.d/MariaDB.repo

# Drop the database (make sure to backup if necessary)
read -sp "Enter root password for SQL: " root_password
echo
mysql -u root -p"$root_password" -e "DROP DATABASE IF EXISTS $dbname;"

# Remove cron job for SpamAssassin updates
crontab -l | grep -v 'sa-update && systemctl reload spamassassin' | crontab -

# Remove SpamAssassin user and group
userdel spamd
groupdel spamd

echo "Uninstallation complete. The system has been reverted to its previous state."
