#!/usr/bin/env bash
# Full outbound-SMTP hijack diagnosis for mail-server VPS (cPanel/Postfix/Exim).
# Run as root OR as ronnie (some checks need root — script will say which).
#
# Usage: bash scripts/diagnose-outbound-smtp-hijack.sh
set -u

HOST="${1:-smtp.gmail.com}"
GOOGLE_IP="$(getent ahostsv4 "${HOST}" 2>/dev/null | awk '{print $1; exit}')"
GOOGLE_IP="${GOOGLE_IP:-142.251.127.109}"

section() { echo ""; echo "========================================"; echo "== $1"; echo "========================================"; }

cert_peek() {
  local target="$1"
  shift
  echo "--- ${target} ---"
  echo | timeout 8 openssl s_client -connect "${target}" "$@" 2>/dev/null \
    | openssl x509 -noout -subject -issuer -ext subjectAltName 2>/dev/null \
    || echo "(connect or cert read failed)"
}

section "1. DNS — does smtp.gmail.com resolve to Google?"
echo "getent ahostsv4 ${HOST}:"
getent ahostsv4 "${HOST}" 2>/dev/null || echo "(getent failed)"
echo "dig +short A ${HOST}:"
dig +short A "${HOST}" 2>/dev/null || host -t A "${HOST}" 2>/dev/null || true
echo "Node resolve4:"
node -e "require('dns').resolve4('${HOST}',(e,a)=>console.log(e||a))" 2>/dev/null || echo "(node not available)"
echo "/etc/hosts grep:"
grep -iE 'gmail|google|smtp' /etc/hosts 2>/dev/null || echo "(no matches)"

section "2. TLS cert — hostname vs Google IP (proves hijack)"
cert_peek "${HOST}:587" "-starttls" "smtp" "-servername" "${HOST}"
cert_peek "${HOST}:465" "-servername" "${HOST}"
cert_peek "${GOOGLE_IP}:587" "-starttls" "smtp" "-servername" "${HOST}"
cert_peek "${GOOGLE_IP}:465" "-servername" "${HOST}"
echo ""
echo "If ALL four show mail.ronnieridge.com → outbound ports 465+587 are redirected to local MTA."
echo "If only hostname tests fail but Google IP works → DNS/hosts hijack only."

section "3. What is listening locally on SMTP ports?"
if command -v ss >/dev/null 2>&1; then
  ss -tlnp | grep -E ':25 |:465 |:587 ' || echo "(nothing on 25/465/587 locally — or need root for -p)"
else
  netstat -tlnp 2>/dev/null | grep -E ':25 |:465 |:587 ' || true
fi

section "4. Which MTA is installed?"
for bin in exim postfix sendmail; do
  command -v "$bin" >/dev/null 2>&1 && echo "found: $(command -v "$bin")"
done
systemctl is-active exim 2>/dev/null && echo "exim: active" || true
systemctl is-active postfix 2>/dev/null && echo "postfix: active" || true

section "5. iptables NAT (needs root — run: sudo bash $0)"
if iptables -t nat -L -n -v 2>/dev/null | head -1 | grep -q Chain; then
  echo "--- nat OUTPUT ---"
  iptables -t nat -L OUTPUT -n -v 2>/dev/null || true
  echo "--- nat PREROUTING ---"
  iptables -t nat -L PREROUTING -n -v 2>/dev/null || true
  echo "--- filter OUTPUT (SMTP ports) ---"
  iptables -L OUTPUT -n -v 2>/dev/null | grep -E '465|587|25|REDIRECT|DNAT' || echo "(no obvious SMTP rules in filter OUTPUT)"
else
  echo "Cannot read iptables (need root). Run as root:"
  echo "  sudo iptables -t nat -L OUTPUT -n -v"
  echo "  sudo iptables -t nat -L PREROUTING -n -v"
fi

section "6. nftables (if used)"
if command -v nft >/dev/null 2>&1; then
  nft list ruleset 2>/dev/null | grep -E '465|587|25|redirect|dnat' || echo "(no SMTP rules or need root)"
else
  echo "nft not installed"
fi

section "7. CSF firewall (common on cPanel)"
if [[ -f /etc/csf/csf.conf ]]; then
  echo "CSF installed. Check:"
  echo "  grep -E '^SMTP|^SMTP_BLOCK|^SMTP_ALLOW' /etc/csf/csf.conf"
  grep -E '^SMTP|^SMTP_BLOCK|^SMTP_ALLOW' /etc/csf/csf.conf 2>/dev/null | head -20 || true
else
  echo "CSF config not found at /etc/csf/csf.conf"
fi

section "8. Exim outbound / smarthost (cPanel default MTA)"
if [[ -f /etc/exim.conf ]]; then
  echo "--- exim manualroute / smarthost hints ---"
  grep -nE 'manualroute|smarthost|route_list|driver = smtp|ignore_fromhost' /etc/exim.conf 2>/dev/null | head -30 || true
fi
if [[ -f /etc/exim.conf.localopts ]]; then
  grep -nE 'relay|smtp|outbound|gmail' /etc/exim.conf.localopts 2>/dev/null | head -20 || true
fi

section "9. Postfix (if present)"
if command -v postconf >/dev/null 2>&1; then
  postconf -n 2>/dev/null | grep -iE 'relayhost|smtp_|mynetworks|inet_interfaces' || true
fi

section "10. TCP connect trace (which local process owns outbound 587?)"
if command -v tcptraceroute >/dev/null 2>&1; then
  tcptraceroute "${GOOGLE_IP}" 587 2>/dev/null | head -5 || true
else
  echo "tcptraceroute not installed (optional)"
fi
echo "Try as root while running openssl in another terminal:"
echo "  ss -tnp | grep -E ':587|:465'"
echo "  lsof -i :587 -i :465 2>/dev/null | head"

section "11. Summary / next steps"
echo "A) If Google IP (${GOOGLE_IP}) tests also show ronnieridge cert:"
echo "   → Fix server: remove iptables REDIRECT / CSF SMTP capture for outbound 465+587."
echo "   → Gmail SMTP cannot work from this VPS until that is fixed."
echo "   → Alternative: run company-api on a non-mail-server host, or use external SMTP relay."
echo ""
echo "B) If Google IP tests show Google cert but hostname tests show ronnieridge:"
echo "   → Fix /etc/hosts or local DNS override for smtp.gmail.com."
echo ""
echo "C) After server fix, set Gmail account: smtp.gmail.com port 465 SSL + App Password."
