#!/bin/bash

# Mail Server Installer for Void Linux with Avahi, Roundcube DB Population, and PAM for Dovecot
# Installs and configures Apache (apache package), MariaDB, Roundcube 1.6.11, Dovecot 2.4.1, PHP 8.4, Postfix, Avahi
# Uses Maildir format, generates self-signed certificates, sets up Roundcube in /srv/www/apache/
# Configures Avahi first for .local domain, autodetects FQDN and .local, updates /etc/hosts, creates and activates services
# Configures Apache to execute PHP files (not display source code), uses mpm_prefork
# Populates Roundcube MySQL database with initial schema
# Uses PAM for Dovecot authentication with system users
# Excludes php-fileinfo installation
# Uses /etc/sv/mysqld for MariaDB service, lets runit manage supervise directory
# Prompts for IP only; Run as sudo ./roundcube_installer_void.sh
# Updated for Dovecot 2.4.1: Replaces mail_location with mail_driver and mail_path

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

# Retry function for starting services
retry_command() {
    local cmd="$1"
    local service_name="$2"
    local max_attempts=3
    local attempt=1

    # Ensure service directory exists
    local service_dir="/etc/sv/$service_name"
    if [ ! -d "$service_dir" ]; then
        echo -e "${RED}Service directory $service_dir does not exist! Cannot start $service_name.${NC}"
        exit 1
    fi

    # Run command with retries, disabling set -e for this block
    set +e
    while [ $attempt -le $max_attempts ]; do
        echo -e "${YELLOW}Attempt $attempt of $max_attempts to start $service_name...${NC}"
        $cmd 2>&1 | tee /tmp/sv_start_$service_name.log
        local exit_status=$?
        if [ $exit_status -eq 0 ] && sv status "$service_name" | grep -q '^run:'; then
            echo -e "${GREEN}$service_name service started successfully.${NC}"
            set -e
            return 0
        else
            echo -e "${RED}Failed to start $service_name (exit status $exit_status). Retrying...${NC}"
            cat /tmp/sv_start_$service_name.log
            sleep 5
            ((attempt++))
        fi
    done
    set -e
    echo -e "${RED}Failed to start $service_name after $max_attempts attempts! Check /tmp/sv_start_$service_name.log and service logs.${NC}"
    exit 1
}

echo -e "${GREEN}Starting Mail Server Installation on Void Linux with Avahi and PAM...${NC}"

# Autodetect FQDN and .local domain
HOSTNAME=$(hostname)
FQDN="${HOSTNAME}.example.com"
DOMAIN="example.com"
LOCAL_FQDN="${HOSTNAME}.local"
echo -e "${GREEN}Autodetected FQDN: $FQDN, Local mDNS: $LOCAL_FQDN${NC}"

# Prompt for server IP
read -p "Enter server IP address [default: 127.0.0.1]: " SERVER_IP
SERVER_IP=${SERVER_IP:-127.0.0.1}
echo -e "${GREEN}Using server IP: $SERVER_IP${NC}"

# Update /etc/hosts
echo -e "${YELLOW}Updating /etc/hosts...${NC}"
if ! grep -q "$FQDN" /etc/hosts; then
    echo "$SERVER_IP $FQDN" >> /etc/hosts
fi
if ! grep -q "$LOCAL_FQDN" /etc/hosts; then
    echo "$SERVER_IP $LOCAL_FQDN" >> /etc/hosts
fi
echo -e "${GREEN}/etc/hosts updated with $FQDN and $LOCAL_FQDN${NC}"

# Update system
echo -e "${YELLOW}Updating system...${NC}"
xbps-install -Syu

# Install packages
echo -e "${YELLOW}Installing packages...${NC}"
xbps-install -S \
    avahi \
    apache \
    mariadb \
    php \
    php-apache \
    php-mysql \
    php-gd \
    php-intl \
    php-devel \
    dovecot \
    postfix \
    openssl \
    wget \
    tar \
    inetutils-telnet \
    net-tools \
    nano \
    pam -y

# Configure Avahi for mDNS
echo -e "${YELLOW}Configuring Avahi for mDNS...${NC}"
mkdir -p /etc/avahi/services
cat > /etc/avahi/services/http.service << EOF
<?xml version="1.0" standalone='no'?>
<!DOCTYPE service-group SYSTEM "avahi-service.dtd">
<service-group>
    <name>$FQDN Mail Server</name>
    <service>
        <type>_http._tcp</type>
        <port>80</port>
    </service>
    <service>
        <type>_https._tcp</type>
        <port>443</port>
    </service>
</service-group>
EOF

chown avahi:avahi /etc/avahi/services/http.service
chmod 644 /etc/avahi/services/http.service

# Enable mDNS resolution in /etc/nsswitch.conf
if ! grep -q "mdns_minimal" /etc/nsswitch.conf; then
    sed -i 's/hosts:.*$/hosts: files mdns_minimal [NOTFOUND=return] dns/' /etc/nsswitch.conf
fi

# Ensure Avahi service is properly set up
echo -e "${YELLOW}Setting up avahi-daemon service...${NC}"

if [ ! -e /var/service/avahi-daemon/supervise ]; then
    # Your code to create or start supervise here
    echo "Creating supervise directory or starting service..."
    # Example:
    ln -s /etc/sv/avahi-daemon /var/service/
else
    echo "Supervise already exists. Skipping."
fi

# Start and enable Avahi with retries
retry_command "sudo /usr/bin/sv start avahi-daemon" "avahi-daemon"

# Ensure MariaDB service is properly set up
# Check and create supervise for mysqld
if [ ! -e /var/service/mysqld/supervise ]; then
    echo "Setting up supervise for mysqld..."
    ln -s /etc/sv/mysqld /var/service/
else
    echo "Supervise for mysqld already exists. Skipping."
fi
echo -e "${YELLOW}Setting up MariaDB service...${NC}"

# Initialize MariaDB data directory
if [ ! -d "/var/lib/mysql/mysql" ]; then
    echo -e "${YELLOW}Initializing MariaDB data directory...${NC}"
    mysql_install_db --user=mysql --basedir=/usr --datadir=/var/lib/mysql
fi
# Ensure mysql user exists
if ! id "mysql" >/dev/null 2>&1; then
    echo -e "${YELLOW}Creating mysql user for MariaDB...${NC}"
    useradd -r -s /sbin/nologin -d /var/lib/mysql mysql
fi
chown -R mysql:mysql /var/lib/mysql
chmod -R 700 /var/lib/mysql

# Start and enable MariaDB with retries
echo -e "${YELLOW}Starting MariaDB service...${NC}"
retry_command "sudo /usr/bin/sv start mysqld" "mysqld"

# Secure MariaDB installation (non-interactive)
echo -e "${YELLOW}Configuring MariaDB root user authentication...${NC}"
sleep 10
mysql -u root -e "ALTER USER 'root'@'localhost' IDENTIFIED VIA mysql_native_password USING PASSWORD(''); FLUSH PRIVILEGES;" || {
    echo -e "${RED}Failed to configure MariaDB root user! Check logs or run 'mysql_secure_installation' manually.${NC}"
    exit 1
}
echo -e "${RED}Secure MariaDB manually with 'mysql_secure_installation' to set a root password and remove test users/databases.${NC}"

# Locate php.ini dynamically
PHP_INI=$(find /etc -name php.ini 2>/dev/null | head -n 1)
if [ -z "$PHP_INI" ]; then
    PHP_INI="/etc/php8.4/php.ini"
    mkdir -p "/etc/php8.4"
    cp "/usr/share/php8.4/php.ini-production" "$PHP_INI" 2>/dev/null || \
    cp /usr/share/php/php.ini-production "$PHP_INI" 2>/dev/null || true
fi
echo -e "${GREEN}Using php.ini: $PHP_INI${NC}"

# Enable required PHP extensions for Roundcube in php.ini
echo -e "${YELLOW}Enabling PHP extensions in $PHP_INI...${NC}"
for ext in mysqli pdo_mysql gd intl mbstring curl iconv dom simplexml openssl; do
    if ! grep -q "^extension=$ext" "$PHP_INI"; then
        sed -i "s|;extension=$ext|extension=$ext|" "$PHP_INI" 2>/dev/null || echo "extension=$ext" >> "$PHP_INI"
    fi
done

# Dynamically find libphp.so path
PHP_MODULE_PATH=$(find /usr -name 'libphp*.so' 2>/dev/null | head -n 1)
if [ -z "$PHP_MODULE_PATH" ]; then
    echo -e "${RED}libphp.so not found! Exiting.${NC}"
    exit 1
fi
echo -e "${GREEN}Using PHP module: $PHP_MODULE_PATH${NC}"

# Dynamically find mod_ssl.so path
SSL_MODULE_PATH=$(find /usr -name 'mod_ssl.so' 2>/dev/null | head -n 1)
if [ -z "$SSL_MODULE_PATH" ]; then
    echo -e "${RED}mod_ssl.so not found! Exiting.${NC}"
    exit 1
fi

# Dynamically find mod_mpm_prefork.so path
PREFORK_MODULE_PATH=$(find /usr -name 'mod_mpm_prefork.so' 2>/dev/null | head -n 1)
if [ -z "$PREFORK_MODULE_PATH" ]; then
    echo -e "${RED}mod_mpm_prefork.so not found! Exiting.${NC}"
    exit 1
fi

# Generate self-signed certificates
echo -e "${YELLOW}Generating self-signed SSL certificates...${NC}"
CERT_PATH="/etc/ssl/certs/$HOSTNAME.example.com.crt"
KEY_PATH="/etc/ssl/private/$HOSTNAME.example.com.key"
if [ ! -f "$CERT_PATH" ] || [ ! -f "$KEY_PATH" ]; then
    echo -e "${RED}SSL certificate or key not found! Generating new ones...${NC}"
    mkdir -p /etc/ssl/certs /etc/ssl/private
    openssl req -new -x509 -days 365 -nodes \
        -out "$CERT_PATH" \
        -keyout "$KEY_PATH" \
        -subj "/C=US/ST=Denial/L=Springfield/O=Dis/CN=$FQDN"
    chmod 644 "$CERT_PATH"
    chmod 600 "$KEY_PATH"
    sudo groupadd dovecot
    chown _dovecot:_dovecot "$CERT_PATH" "$KEY_PATH"
fi

# Generate Dovecot SSL certificates
mkdir -p /etc/dovecot/
openssl req -new -x509 -nodes -out /etc/dovecot/ssl-cert.pem -keyout /etc/dovecot/ssl-key.pem -days 365 -subj "/C=US/ST=Denial/L=Springfield/O=Dis/CN=$FQDN"
chown _dovecot:_dovecot /etc/dovecot/ssl-cert.pem /etc/dovecot/ssl-key.pem
chmod 644 /etc/dovecot/ssl-cert.pem
chmod 600 /etc/dovecot/ssl-key.pem

# Download and install Roundcube 1.6.11
echo -e "${YELLOW}Installing Roundcube 1.6.11...${NC}"
cd /tmp
wget -q https://github.com/roundcube/roundcubemail/releases/download/1.6.11/roundcubemail-1.6.11-complete.tar.gz
tar -xzf roundcubemail-1.6.11-complete.tar.gz
rm -rf /srv/www/apache/roundcube
mv roundcubemail-1.6.11 /srv/www/apache/roundcube
chown -R _apache:_apache /srv/www/apache/roundcube
chmod -R 755 /srv/www/apache/roundcube
sudo chmod -R 775 /srv/www/apache/roundcube/logs
sudo chmod -R 775 /srv/www/apache/roundcube/temp

# Create and populate Roundcube database
echo -e "${YELLOW}Setting up Roundcube database...${NC}"
DB_USER="roundcube"
DB_NAME="roundcube"
DB_PASS="roundcube_pass_$(openssl rand -hex 8)"
echo -e "${GREEN}Roundcube DB password: $DB_PASS${NC}"
printf "Generated password (raw): '%s'\n" "$DB_PASS" > /tmp/roundcube_db_pass.log

# Drop existing database to ensure clean state
echo -e "${YELLOW}Dropping existing Roundcube database if it exists...${NC}"
mysql -u root -e "DROP DATABASE IF EXISTS $DB_NAME;" 2>/tmp/mysql_error.log || {
    echo -e "${RED}Failed to drop existing Roundcube database! Check /tmp/mysql_error.log and /var/log/mariadb/mariadb.log.${NC}"
    cat /tmp/mysql_error.log
    exit 1
}

# Create database and user with explicit mysql_native_password
echo -e "${YELLOW}Creating Roundcube database and user...${NC}"
printf "Executing MySQL command with password: '%s'\n" "$DB_PASS" >> /tmp/roundcube_db_pass.log
mysql -u root -e "CREATE DATABASE $DB_NAME;
DROP USER IF EXISTS '$DB_USER'@'localhost';
CREATE USER '$DB_USER'@'localhost' IDENTIFIED VIA mysql_native_password USING PASSWORD('$DB_PASS');
GRANT ALL PRIVILEGES ON $DB_NAME.* TO '$DB_USER'@'localhost';
FLUSH PRIVILEGES;" 2>/tmp/mysql_error.log || {
    echo -e "${RED}Failed to create Roundcube database or user! Check /tmp/mysql_error.log and /var/log/mariadb/mariadb.log.${NC}"
    cat /tmp/mysql_error.log
    exit 1
}

# Verify user creation
echo -e "${YELLOW}Verifying Roundcube user creation...${NC}"
USER_CHECK=$(mysql -u root -e "SELECT User, Host, plugin FROM mysql.user WHERE User='$DB_USER' AND Host='localhost';" | grep roundcube)
if [ -z "$USER_CHECK" ]; then
    echo -e "${RED}Roundcube user not found in MySQL!${NC}"
    exit 1
fi
echo -e "${GREEN}Roundcube user $DB_USER verified: $USER_CHECK${NC}"

# Test credentials
echo -e "${YELLOW}Testing Roundcube user credentials...${NC}"
printf "Testing login: mysql -u %s --password='%s' -e 'SELECT 1;' %s\n" "$DB_USER" "$DB_PASS" "$DB_NAME" >> /tmp/roundcube_db_pass.log
if ! mysql -u "$DB_USER" --password="$DB_PASS" -e "SELECT 1;" "$DB_NAME" 2>/tmp/mysql_error.log; then
    echo -e "${RED}Failed to log in as $DB_USER! Check /tmp/mysql_error.log and /tmp/roundcube_db_pass.log.${NC}"
    cat /tmp/mysql_error.log
    exit 1
fi
echo -e "${GREEN}Roundcube user credentials tested successfully.${NC}"

# Populate database
ROUNDCUBE_SQL="/srv/www/apache/roundcube/SQL/mysql.initial.sql"
if [ -f "$ROUNDCUBE_SQL" ]; then
    echo -e "${YELLOW}Populating Roundcube database...${NC}"
    printf "Populating database: mysql -u %s --password='%s' %s < %s\n" "$DB_USER" "$DB_PASS" "$DB_NAME" "$ROUNDCUBE_SQL" >> /tmp/roundcube_db_pass.log
    mysql -u "$DB_USER" --password="$DB_PASS" "$DB_NAME" < "$ROUNDCUBE_SQL" 2>/tmp/mysql_error.log || {
        echo -e "${RED}Failed to populate Roundcube database! Check $ROUNDCUBE_SQL, /tmp/mysql_error.log, and MySQL permissions.${NC}"
        cat /tmp/mysql_error.log
        exit 1
    }
    echo -e "${GREEN}Roundcube database populated successfully.${NC}"
else
    echo -e "${RED}Roundcube SQL file ($ROUNDCUBE_SQL) not found! Skipping database population.${NC}"
    exit 1
fi

# Configure Roundcube
cd /srv/www/apache/roundcube
cp config/config.inc.php.sample config/config.inc.php
sed -i "s|'mysql://[^']*'|\"mysql://$DB_USER:$DB_PASS@localhost/$DB_NAME\"|" config/config.inc.php

# Add Roundcube-specific config for IMAP/SMTP (Dovecot/Postfix)
cat >> config/config.inc.php << EOF
\$config['default_host'] = 'ssl://$LOCAL_FQDN';
\$config['default_port'] = 993;
\$config['smtp_server'] = 'tls://$LOCAL_FQDN';
\$config['smtp_port'] = 587;
\$config['smtp_user'] = '%u';
\$config['smtp_pass'] = '%p';
\$config['des_key'] = '$(openssl rand -base64 24)';
\$config['skin'] = 'elastic';
\$config['enable_spellcheck'] = true;
\$config['plugins'] = array('archive', 'zipdownload');
\$config['mail_domain'] = '%d';
\$config['create_default_identity'] = true;
EOF

# Apache configuration
echo -e "${YELLOW}Configuring Apache...${NC}"
sed -i 's|^LoadModule mpm_event_module|#LoadModule mpm_event_module|' /etc/apache/httpd.conf
sed -i 's|^LoadModule mpm_worker_module|#LoadModule mpm_worker_module|' /etc/apache/httpd.conf
echo "LoadModule mpm_prefork_module $PREFORK_MODULE_PATH" >> /etc/apache/httpd.conf
echo "LoadModule ssl_module $SSL_MODULE_PATH" >> /etc/apache/httpd.conf

# Create Apache PHP configuration
mkdir -p /etc/apache/extra
cat > /etc/apache/extra/php.conf << EOF
LoadModule php_module $PHP_MODULE_PATH
AddType application/x-httpd-php .php
DirectoryIndex index.php index.html
<FilesMatch \.php$>
    SetHandler application/x-httpd-php
</FilesMatch>
EOF

# Create Apache Roundcube configuration
cat > /etc/apache/extra/roundcube.conf << EOF
Alias /webmail /srv/www/apache/roundcube
<Directory /srv/www/apache/roundcube>
    Options -Indexes +FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>
EOF

# Create Apache SSL configuration
cat > /etc/apache/extra/mail-ssl.conf << EOF
Listen 443
<VirtualHost *:443>
    ServerName $FQDN
    DocumentRoot /srv/www/apache
    SSLEngine on
    SSLCertificateFile $CERT_PATH
    SSLCertificateKeyFile $KEY_PATH
    <Directory /srv/www/apache>
        Options -Indexes +FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>
EOF

# Include Apache configurations
for conf in php.conf roundcube.conf mail-ssl.conf; do
    if [ -f "/etc/apache/extra/$conf" ]; then
        if ! grep -q "Include /etc/apache/extra/$conf" /etc/apache/httpd.conf; then
            echo "Include /etc/apache/extra/$conf" >> /etc/apache/httpd.conf
        fi
    else
        echo -e "${RED}Configuration file /etc/apache/extra/$conf not found! Exiting.${NC}"
        exit 1
    fi
done

# Ensure Apache service is properly set up
echo -e "${YELLOW}Setting up Apache service...${NC}"
sudo ln -sf /etc/sv/apache /var/service/

# Start Apache with retries
retry_command "sudo /usr/bin/sv start apache" "apache"

# Configure Dovecot
echo -e "${YELLOW}Configuring Dovecot...${NC}"
sudo ln -sf /etc/sv/dovecot /var/service/

mkdir -p /etc/dovecot/conf.d
if [ -f "/usr/share/examples/dovecot/dovecot.conf" ]; then
    cp /usr/share/examples/dovecot/dovecot.conf /etc/dovecot/
else
    echo "!include conf.d/*.conf" > /etc/dovecot/dovecot.conf
fi
cat >> /etc/dovecot/dovecot.conf << EOF
ssl_server {
  cert_file = /etc/dovecot/ssl-cert.pem
  key_file = /etc/dovecot/ssl-key.pem
}
mail_home = /home/%{user}
mail_driver = maildir
mail_path = /home/%{user}/Maildir
EOF
chown root:root /etc/dovecot/dovecot.conf
chmod 644 /etc/dovecot/dovecot.conf

# Configure Dovecot mail settings for 2.4.1
cat > /etc/dovecot/conf.d/10-mail.conf << EOF
mail_driver = maildir
mail_path = ~/Maildir
mail_control_path = /var/no-quota/%{user}
namespace inbox {
  separator = .
  prefix =
  inbox = yes
}
EOF

cat > /etc/dovecot/conf.d/15-mailboxes.conf << EOF
namespace inbox {
  inbox = yes

  mailbox Sent {
    auto = subscribe
  }
  mailbox Drafts {
    auto = subscribe
  }
  mailbox Trash {
    auto = subscribe
  }
  mailbox Junk {
    auto = subscribe
  }
}
EOF

sudo chown root:root /etc/dovecot/conf.d/15-mailboxes.conf
sudo chmod 644 /etc/dovecot/conf.d/15-mailboxes.conf

sudo mkdir -p /var/no-quota
sudo chmod 755 /var/no-quota

# Create directories in /var/no-quota for each real user
# Make sure script is run as root
if [ "$(id -u)" -ne 0 ]; then
  echo "Please run as root."
  exit 1
fi

getent passwd | while IFS=: read -r user _ uid gid _ home shell; do
  # Skip system users and nobody
  if [ "$uid" -lt 1000 ] || [ "$user" = "nobody" ]; then
    continue
  fi

  # Only users with home under /home/
  if [[ "$home" != /home/* ]]; then
    continue
  fi

  dir="/var/no-quota/$user"

  if [ -d "$dir" ]; then
    echo "Skipping $user: $dir already exists."
  else
    mkdir -p "$dir"
    chown "$user:$user" "$dir"
    chmod 755 "$dir"
    echo "Created and configured $dir for $user"
  fi
done

chown root:root /etc/dovecot/conf.d/10-mail.conf
chmod 644 /etc/dovecot/conf.d/10-mail.conf
# Check for hidden characters in 10-mail.conf
echo -e "${YELLOW}Checking /etc/dovecot/conf.d/10-mail.conf for hidden characters...${NC}"
cat -v /etc/dovecot/conf.d/10-mail.conf
# Ensure Unix line endings
if command -v dos2unix >/dev/null 2>&1; then
    dos2unix /etc/dovecot/conf.d/10-mail.conf 2>/dev/null || true
fi

# Configure Dovecot authentication
cat > /etc/dovecot/conf.d/10-auth.conf << EOF
auth_mechanisms = plain login
auth_allow_cleartext = no
passdb pam {
  driver = pam
}
userdb passwd {
  driver = passwd
}
EOF
chown root:root /etc/dovecot/conf.d/10-auth.conf
chmod 644 /etc/dovecot/conf.d/10-auth.conf

# Configure Dovecot SSL
cat > /etc/dovecot/conf.d/10-ssl.conf << EOF
ssl = required
ssl_server_cert_file = $CERT_PATH
ssl_server_key_file = $KEY_PATH
ssl_min_protocol = TLSv1.2
ssl_cipher_list = ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384
ssl_server_prefer_ciphers = server
EOF
chown root:root /etc/dovecot/conf.d/10-ssl.conf
chmod 644 /etc/dovecot/conf.d/10-ssl.conf

# Configure Dovecot master settings
cat > /etc/dovecot/conf.d/10-master.conf << EOF
service imap-login {
  inet_listener imap {
    port = 143
  }
  inet_listener imaps {
    port = 993
    ssl = yes
  }
}
service lmtp {
  unix_listener lmtp {
    mode = 0666
  }
}
service auth {
  unix_listener auth-userdb {
    mode = 0666
  }
  unix_listener /var/spool/postfix/private/auth {
    mode = 0660
    user = postfix
    group = postfix
  }
}
EOF
chown root:root /etc/dovecot/conf.d/10-master.conf
chmod 644 /etc/dovecot/conf.d/10-master.conf

# Configure PAM for Dovecot
if [ ! -f "/etc/pam.d/dovecot" ]; then
    echo -e "${RED}PAM configuration file /etc/pam.d/dovecot not found! Creating it...${NC}"
    cat > /etc/pam.d/dovecot << EOF
auth    required    pam_unix.so nullok
account required    pam_unix.so
session required    pam_unix.so
EOF
    chmod 644 /etc/pam.d/dovecot
fi

# Ensure Dovecot service is properly set up
echo -e "${YELLOW}Setting up Dovecot service...${NC}"
rm -rf /var/service/dovecot
sudo ln -s /etc/sv/dovecot /var/service/

# Start Dovecot with retries
retry_command "sudo /usr/bin/sv start dovecot" "dovecot"

# Ensure postfix user and group exist
if ! id postfix >/dev/null 2>&1; then
    echo -e "${YELLOW}Creating postfix user and group...${NC}"
    groupadd -r postfix
    useradd -r -s /sbin/nologin -d /var/spool/postfix -g postfix postfix
fi

# Configure Postfix
echo -e "${YELLOW}Configuring Postfix...${NC}"
postconf -e "myhostname = $FQDN"
postconf -e "mydomain = $DOMAIN"
postconf -e "myorigin = $DOMAIN"
postconf -e "inet_interfaces = all"
postconf -e "mydestination = $FQDN, localhost.$DOMAIN, localhost, $LOCAL_FQDN"
postconf -e "home_mailbox = Maildir/"
postconf -e "smtpd_tls_cert_file = $CERT_PATH"
postconf -e "smtpd_tls_key_file = $KEY_PATH"
postconf -e "smtpd_use_tls = yes"
postconf -e "smtp_tls_security_level = may"
postconf -e "smtpd_sasl_auth_enable = yes"
postconf -e "smtpd_sasl_type = dovecot"
postconf -e "smtpd_sasl_path = private/auth"
postconf -e "smtpd_recipient_restrictions = permit_sasl_authenticated, permit_mynetworks, reject_unauth_destination"

# Uncomment smtp in master.cf
sed -i '/submission/ s/^#//' /etc/postfix/master.cf

# Ensure Postfix service directory exists
echo -e "${YELLOW}Setting up Postfix service...${NC}"
if [ ! -d "/etc/sv/postfix" ]; then
    echo -e "${RED}Postfix service directory /etc/sv/postfix not found! Attempting to create it...${NC}"
    mkdir -p /etc/sv/postfix
    cat > /etc/sv/postfix/run << 'EOF'
#!/bin/sh
exec /usr/sbin/postfix start 2>&1
EOF
    chmod 755 /etc/sv/postfix/run
    chown root:root /etc/sv/postfix
fi

# Ensure symbolic link
sudo ln -sf /etc/sv/postfix /var/service/

# Start Postfix with retries
retry_command "sudo /usr/bin/sv start postfix" "postfix"

# Final instructions
echo -e "${GREEN}Mail server installation completed!${NC}"
echo -e "${YELLOW}Next steps:${NC}"
echo -e "1. Access Roundcube at https://$FQDN/roundcube"
echo -e "2. Configure DNS MX records for $DOMAIN"
echo -e "3. Secure MariaDB with 'mysql_secure_installation'"
echo -e "4. Check Dovecot config: cat /tmp/dovecot-config.log"
echo -e "5. Check logs: /var/log/dovecot.log, /var/log/maillog, /var/log/apache/error.log, /tmp/sv_start_avahi-daemon.log, /tmp/sv_start_mysqld.log, /tmp/sv_start_apache.log, /tmp/sv_start_dovecot.log, /tmp/sv_start_postfix.log"
echo -e "6. For production, consider using mail_path = /var/mail/vhosts/%{domain}/%{user} for virtual users"
