#!/usr/bin/env bash
# Email authentication checker — validates SPF, DKIM, DMARC for a domain.
# Usage: bash scripts/check_email_auth.sh example.com
set -euo pipefail

DOMAIN="${1:?Usage: $0 <domain>}"

echo "=== Email Authentication Check for $DOMAIN ==="
echo ""

echo "--- SPF Record ---"
SPF=$(dig +short TXT "$DOMAIN" | grep -i "v=spf1" || echo "NOT FOUND")
echo "  $SPF"
if echo "$SPF" | grep -q "~all"; then
  echo "  ⚠️  WARNING: Soft fail (~all) — should be hard fail (-all)"
elif echo "$SPF" | grep -q "\-all"; then
  echo "  ✅ Hard fail (-all) configured"
elif echo "$SPF" | grep -q "+all"; then
  echo "  🔴 CRITICAL: +all allows any sender!"
fi

echo ""
echo "--- DMARC Record ---"
DMARC=$(dig +short TXT "_dmarc.$DOMAIN" | grep -i "v=dmarc1" || echo "NOT FOUND")
echo "  $DMARC"
if echo "$DMARC" | grep -q "p=reject"; then
  echo "  ✅ Policy: reject"
elif echo "$DMARC" | grep -q "p=quarantine"; then
  echo "  🟡 Policy: quarantine (good, but reject is better)"
elif echo "$DMARC" | grep -q "p=none"; then
  echo "  ⚠️  WARNING: Policy is none (monitoring only, not enforcing)"
fi

echo ""
echo "--- DKIM Selectors (common) ---"
for sel in google default selector1 selector2 dkim s1 s2 mail; do
  DKIM=$(dig +short TXT "${sel}._domainkey.${DOMAIN}" 2>/dev/null)
  if [ -n "$DKIM" ]; then
    echo "  ✅ Found DKIM selector: $sel"
  fi
done

echo ""
echo "--- BIMI Record ---"
BIMI=$(dig +short TXT "default._bimi.$DOMAIN" 2>/dev/null || echo "")
if [ -n "$BIMI" ]; then
  echo "  ✅ BIMI configured: $BIMI"
else
  echo "  ℹ️  No BIMI record (optional)"
fi

echo ""
echo "--- MTA-STS ---"
MTASTS=$(dig +short TXT "_mta-sts.$DOMAIN" 2>/dev/null || echo "")
if [ -n "$MTASTS" ]; then
  echo "  ✅ MTA-STS configured"
else
  echo "  ℹ️  No MTA-STS (recommended for transport encryption)"
fi
