#!/bin/bash

set -euo pipefail
IFS=$'\n\t'

if [[ $EUID -ne 0 ]]; then
    echo "This script must be run as root"
    exit 1
fi

CURRENT_USER="$SUDO_USER"
if [ -z "$CURRENT_USER" ]; then
    echo "Please run this script using sudo"
    exit 1
fi

export DEBIAN_FRONTEND=noninteractive
apt-get update
apt-get install -y postfix mailutils

cat > /etc/postfix/main.cf <<EOF
smtpd_banner = \$myhostname ESMTP \$mail_name
biff = no
append_dot_mydomain = no
readme_directory = no

inet_interfaces = loopback-only
inet_protocols = all
myhostname = devsecops.local
mydestination = \$myhostname, localhost.\$mydomain, localhost
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
mailbox_size_limit = 0
recipient_delimiter = +
mail_spool_directory = /var/mail
EOF

# Create and set permissions for mail directory
touch "/var/mail/$CURRENT_USER"
chown "$CURRENT_USER:mail" "/var/mail/$CURRENT_USER"
chmod 660 "/var/mail/$CURRENT_USER"

systemctl restart postfix

echo "Test message" | mail -s "Mail Setup Test" "$CURRENT_USER"

echo "Setup complete!"
echo "Mail is configured for user: $CURRENT_USER"
echo "To check your mail, run: mail"
