#!/usr/bin/env bash
set -euo pipefail

usage() {
    cat <<'EOF'
Usage: scripts/email-server {install|status}

Install an idempotent Postfix + Dovecot baseline on the OCI email VM.
Set LAB_EMAIL_DOMAIN when the mail domain is available. Mail ingress remains
closed unless LAB_EMAIL_OPEN_MAIL_PORTS=true is explicitly set.
EOF
}

action="${1:-install}"
if [[ "${action}" != install && "${action}" != status ]]; then
    usage >&2
    exit 2
fi

repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
stack="${repo_root}/bootstrap/oci"
email_ip="${LAB_EMAIL_PUBLIC_IP:-}"
if [[ -z "${email_ip}" ]]; then
    email_ip="$(tofu -chdir="${stack}" output -raw email_public_ip 2>/dev/null || true)"
fi
[[ -n "${email_ip}" && "${email_ip}" != null ]] || {
    echo 'Email public IP is unavailable. Apply the OCI foundation first.' >&2
    exit 1
}

ssh_user="${LAB_EMAIL_SSH_USER:-ubuntu}"
ssh_key="${LAB_EMAIL_SSH_PRIVATE_KEY:-${HOME}/.ssh/id_ed25519}"
ssh_target="${ssh_user}@${email_ip}"
ssh_opts=(-i "${ssh_key}" -o ConnectTimeout=15 -o StrictHostKeyChecking=accept-new)

if [[ "${action}" == status ]]; then
    ssh "${ssh_opts[@]}" "${ssh_target}" 'sudo systemctl is-active postfix dovecot fail2ban prometheus-node-exporter; sudo postfix check; sudo ss -ltnp | grep -E ":(25|465|587|993|9100)\b" || true'
    exit $?
fi

domain="${LAB_EMAIL_DOMAIN:-}"
open_mail="${LAB_EMAIL_OPEN_MAIL_PORTS:-false}"
monitoring_cidr="${LAB_OCI_EMAIL_MONITORING_CIDR:-${LAB_OCI_MONITORING_CIDR:-${LAB_OCI_ADMIN_CIDR:-}}}"
echo "Preparing Postfix and Dovecot on ${ssh_target} (domain=${domain:-pending}, mail_ports=${open_mail})."
ssh "${ssh_opts[@]}" "${ssh_target}" sudo bash -s -- "${domain}" "${open_mail}" "${monitoring_cidr}" <<'REMOTE'
set -euo pipefail
domain="${1:-}"
open_mail="${2:-false}"
monitoring_cidr="${3:-}"
hostname_value="${domain:+mail.${domain}}"
hostname_value="${hostname_value:-homelab-mail}"

export DEBIAN_FRONTEND=noninteractive
echo 'postfix postfix/mailname string' | debconf-set-selections
echo 'postfix postfix/main_mailer_type select Internet Site' | debconf-set-selections
apt-get update
apt-get install -y postfix dovecot-imapd dovecot-lmtpd fail2ban ufw openssl prometheus-node-exporter

hostnamectl set-hostname "${hostname_value}" 2>/dev/null || true
printf '%s\n' "${hostname_value}" >/etc/mailname

install -d -m 0750 /etc/ssl/private /etc/ssl/certs
if [[ ! -s /etc/ssl/private/homelab-mail.key || ! -s /etc/ssl/certs/homelab-mail.crt ]]; then
    openssl req -x509 -nodes -newkey rsa:2048 -days 825 \
        -keyout /etc/ssl/private/homelab-mail.key \
        -out /etc/ssl/certs/homelab-mail.crt \
        -subj "/CN=${hostname_value}" >/dev/null 2>&1
    chmod 0600 /etc/ssl/private/homelab-mail.key
fi

postconf -e "myhostname = ${hostname_value}"
postconf -e "mydomain = ${domain:-localdomain}"
postconf -e 'myorigin = $mydomain'
postconf -e 'inet_interfaces = all'
postconf -e 'inet_protocols = ipv4'
postconf -e 'home_mailbox = Maildir/'
postconf -e 'disable_vrfy_command = yes'
postconf -e 'smtpd_recipient_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination'
postconf -e 'smtpd_tls_security_level = may'
postconf -e 'smtpd_tls_auth_only = yes'
postconf -e 'smtpd_tls_cert_file = /etc/ssl/certs/homelab-mail.crt'
postconf -e 'smtpd_tls_key_file = /etc/ssl/private/homelab-mail.key'
postconf -e 'smtpd_sasl_auth_enable = yes'
postconf -e 'smtpd_sasl_type = dovecot'
postconf -e 'smtpd_sasl_path = private/auth'
postconf -e 'smtpd_sasl_security_options = noanonymous'

cat >/etc/dovecot/conf.d/99-homelab-mail.conf <<EOF
protocols = imap lmtp
listen = *
mail_location = maildir:~/Maildir
auth_mechanisms = plain login
ssl = required
ssl_cert = </etc/ssl/certs/homelab-mail.crt
ssl_key = </etc/ssl/private/homelab-mail.key
service auth {
  unix_listener /var/spool/postfix/private/auth {
    mode = 0660
    user = postfix
    group = postfix
  }
}
EOF

ufw --force reset >/dev/null
ufw default deny incoming
ufw default allow outgoing
ufw allow 22/tcp
if [[ -n "${monitoring_cidr}" ]]; then
    ufw allow from "${monitoring_cidr}" to any port 9100 proto tcp
fi
if [[ "${open_mail}" == true ]]; then
    ufw allow 25/tcp
    ufw allow 465/tcp
    ufw allow 587/tcp
    ufw allow 993/tcp
fi
ufw --force enable >/dev/null

systemctl enable --now postfix dovecot fail2ban prometheus-node-exporter
systemctl restart postfix dovecot
postfix check
systemctl is-active postfix dovecot fail2ban
echo "Email baseline ready. Domain-dependent DNS, PTR, DKIM, DMARC, and trusted TLS remain to be configured."
REMOTE
