#!/usr/bin/env bash
# Fix Contabo/VPS outbound SMTP hijack: local Postfix answers on 25/465/587 with the VPS cert
# instead of letting traffic reach Gmail. Run on the API server as root.
set -euo pipefail

echo "== Outbound SMTP egress check =="

for port in 25 465 587; do
  echo "--- listeners on :${port} ---"
  ss -tlnp | grep ":${port} " || echo "(none)"
done

echo "--- NAT redirects (iptables) ---"
if command -v iptables >/dev/null 2>&1; then
  iptables -t nat -L -n -v 2>/dev/null | grep -E ':(25|465|587)\b' || echo "(no matching NAT rules)"
else
  echo "iptables not installed"
fi

if command -v postconf >/dev/null 2>&1; then
  echo "--- Postfix inet_interfaces (before) ---"
  postconf inet_interfaces
  echo "Restricting Postfix to loopback only..."
  postconf -e 'inet_interfaces = loopback-only'
  postconf -e 'inet_protocols = ipv4'
  systemctl restart postfix 2>/dev/null || service postfix restart 2>/dev/null || true
  echo "--- Postfix inet_interfaces (after) ---"
  postconf inet_interfaces
else
  echo "Postfix not found — skip"
fi

if command -v exim >/dev/null 2>&1; then
  echo "Exim detected — disable or bind to localhost only (manual step may be required)"
fi

echo "--- TLS probe to Gmail (expect Google cert, not contaboserver) ---"
if command -v openssl >/dev/null 2>&1; then
  echo | openssl s_client -connect smtp.gmail.com:465 -servername smtp.gmail.com 2>/dev/null \
    | openssl x509 -noout -subject -issuer -ext subjectAltName 2>/dev/null \
    || echo "openssl probe failed"
else
  echo "openssl not installed"
fi

echo ""
echo "Done. If subject still shows contaboserver.net, remove iptables REDIRECT rules or stop the local MTA."
echo "Then retry Company SMTP → Test connection in the app."
