#!/usr/bin/env bash
# Run on the company-api server when Gmail SMTP probe shows mail.ronnieridge.com cert.
set -euo pipefail

HOST="${1:-smtp.gmail.com}"
GOOGLE_IP="$(host -t A "${HOST}" 2>/dev/null | awk '/has address/ {print $4; exit}')"
GOOGLE_IP="${GOOGLE_IP:-142.251.127.109}"

echo "== DNS A (IPv4) for ${HOST} =="
host -t A "${HOST}" 2>/dev/null || nslookup -type=A "${HOST}" 2>/dev/null || true

echo ""
echo "== Node.js resolve4 =="
node -e "require('dns').resolve4('${HOST}', (e,a)=>console.log(e||a))"

cert_summary() {
  echo | openssl s_client -connect "$1" -servername "${HOST}" "$2" 2>/dev/null \
    | openssl x509 -noout -subject -ext subjectAltName 2>/dev/null || echo "(no cert)"
}

echo ""
echo "== Port 587 STARTTLS via hostname (often hijacked on mail-server VPS) =="
cert_summary "${HOST}:587" "-starttls smtp"

echo ""
echo "== Port 587 STARTTLS via Google IP ${GOOGLE_IP} (proves hijack if local cert) =="
cert_summary "${GOOGLE_IP}:587" "-starttls smtp"

echo ""
echo "== Port 465 SSL via hostname (Gmail workaround — use this in the app) =="
cert_summary "${HOST}:465" ""

echo ""
if cert_summary "${HOST}:587" "-starttls smtp" 2>/dev/null | grep -qi ronnieridge; then
  echo "DIAGNOSIS: Outbound port 587 is hijacked by your local mail server."
  echo "FIX: Set Gmail SMTP to port 465 / SSL in Company SMTP settings, then Probe Health again."
else
  echo "Port 587 looks OK from this host. If the app still fails, check PM2 logs."
fi
