#!/bin/bash
# ---------------------------------------------------------------
#  forensic-report.sh — Full forensic dump of the DMARC lab
# ---------------------------------------------------------------
#
#  Run from receiver-mta (or any container with DNS access):
#    docker compose exec receiver-mta bash /scripts/forensic-report.sh
#
#  Generates a timestamped text report with:
#    1. DNS records (SPF, DKIM, DMARC) for all domains
#    2. Mail log analysis
#    3. Authentication-Results from delivered mail
#    4. OpenDMARC history/aggregate data
#    5. Summary statistics
# ---------------------------------------------------------------

REPORT_DIR="/tmp/forensic-reports"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
REPORT="${REPORT_DIR}/forensic_${TIMESTAMP}.txt"
MAILBOX="/var/mail/bob"
LOGFILE="/var/log/mail.log"
DMARC_HIST="/var/run/opendmarc/opendmarc.dat"
DNS_SERVER="10.0.0.2"

mkdir -p "$REPORT_DIR"

# Helper
separator() {
    echo "----------------------------------------------------" >> "$REPORT"
}

section() {
    echo "" >> "$REPORT"
    separator
    echo "  $1" >> "$REPORT"
    separator
    echo "" >> "$REPORT"
}

{
echo "DMARC Lab - Forensic Report"
echo "Generated: $(date)"
echo "Hostname:  $(hostname)"
echo "IP:        $(hostname -I 2>/dev/null || echo 'unknown')"
} > "$REPORT"

# -- 1. DNS Records --
section "1. DNS RECORDS"

for DOMAIN in legit.lab thirdparty.lab misconf.lab evil.lab receiver.lab; do
    echo "--- ${DOMAIN} ---" >> "$REPORT"

    echo "  MX:" >> "$REPORT"
    dig @${DNS_SERVER} ${DOMAIN} MX +short 2>/dev/null >> "$REPORT" || echo "  (query failed)" >> "$REPORT"

    echo "  A:" >> "$REPORT"
    dig @${DNS_SERVER} mail.${DOMAIN} A +short 2>/dev/null >> "$REPORT" || echo "  (query failed)" >> "$REPORT"

    echo "  SPF (TXT):" >> "$REPORT"
    dig @${DNS_SERVER} ${DOMAIN} TXT +short 2>/dev/null | grep -i spf >> "$REPORT" || echo "  (none)" >> "$REPORT"

    echo "  DKIM (selector1._domainkey):" >> "$REPORT"
    dig @${DNS_SERVER} selector1._domainkey.${DOMAIN} TXT +short 2>/dev/null >> "$REPORT" || echo "  (none)" >> "$REPORT"

    echo "  DMARC (_dmarc):" >> "$REPORT"
    dig @${DNS_SERVER} _dmarc.${DOMAIN} TXT +short 2>/dev/null >> "$REPORT" || echo "  (none)" >> "$REPORT"

    echo "" >> "$REPORT"
done

# -- 2. Mail Log Analysis --
section "2. MAIL LOG ANALYSIS"

if [ -f "$LOGFILE" ]; then
    echo "--- SPF Events ---" >> "$REPORT"
    grep -i "policyd-spf\|Received-SPF" "$LOGFILE" 2>/dev/null >> "$REPORT" || echo "  (none)" >> "$REPORT"

    echo "" >> "$REPORT"
    echo "--- DKIM Events ---" >> "$REPORT"
    grep -i "opendkim\|DKIM" "$LOGFILE" 2>/dev/null >> "$REPORT" || echo "  (none)" >> "$REPORT"

    echo "" >> "$REPORT"
    echo "--- DMARC Events ---" >> "$REPORT"
    grep -i "opendmarc\|dmarc" "$LOGFILE" 2>/dev/null >> "$REPORT" || echo "  (none)" >> "$REPORT"

    echo "" >> "$REPORT"
    echo "--- Delivery / Reject Events ---" >> "$REPORT"
    grep -iE "status=|reject|550|451|dsn=" "$LOGFILE" 2>/dev/null >> "$REPORT" || echo "  (none)" >> "$REPORT"
else
    echo "  Log file not found: ${LOGFILE}" >> "$REPORT"
fi

# -- 3. Delivered Mail Headers --
section "3. DELIVERED MAIL HEADERS"

if [ -f "$MAILBOX" ] && [ -s "$MAILBOX" ]; then
    # Extract full headers of all messages
    awk '/^From /{p=1; print "--- Message ---"} p && /^$/{p=0} p{print}' "$MAILBOX" >> "$REPORT"
else
    echo "  No delivered mail in ${MAILBOX}" >> "$REPORT"
    echo "  (Rejected emails have no headers - check logs above)" >> "$REPORT"
fi

# -- 4. OpenDMARC History Data --
section "4. OPENDMARC HISTORY (AGGREGATE DATA)"

if [ -f "$DMARC_HIST" ] && [ -s "$DMARC_HIST" ]; then
    cat "$DMARC_HIST" >> "$REPORT"
else
    echo "  No DMARC history data yet (${DMARC_HIST})" >> "$REPORT"
fi

# -- 5. Summary Statistics --
section "5. SUMMARY STATISTICS"

if [ -f "$LOGFILE" ]; then
    TOTAL_CONN=$(grep -c "connect from" "$LOGFILE" 2>/dev/null || echo 0)
    SPF_PASS=$(grep -ci "spf=pass\|Received-SPF: Pass" "$LOGFILE" 2>/dev/null || echo 0)
    SPF_FAIL=$(grep -ci "spf=fail\|spf=none" "$LOGFILE" 2>/dev/null || echo 0)
    DKIM_PASS=$(grep -ci "dkim=pass" "$LOGFILE" 2>/dev/null || echo 0)
    DKIM_FAIL=$(grep -ci "dkim=fail\|dkim=none" "$LOGFILE" 2>/dev/null || echo 0)
    DMARC_PASS=$(grep -ci "dmarc=pass" "$LOGFILE" 2>/dev/null || echo 0)
    DMARC_FAIL=$(grep -ci "dmarc=fail" "$LOGFILE" 2>/dev/null || echo 0)
    REJECTS=$(grep -ci "reject\|550" "$LOGFILE" 2>/dev/null || echo 0)
    DELIVERED=$(grep -ci "status=sent" "$LOGFILE" 2>/dev/null || echo 0)

    {
    echo "  Total SMTP connections:  ${TOTAL_CONN}"
    echo "  SPF pass / fail|none:    ${SPF_PASS} / ${SPF_FAIL}"
    echo "  DKIM pass / fail|none:   ${DKIM_PASS} / ${DKIM_FAIL}"
    echo "  DMARC pass / fail:       ${DMARC_PASS} / ${DMARC_FAIL}"
    echo "  Messages delivered:      ${DELIVERED}"
    echo "  Messages rejected:       ${REJECTS}"
    } >> "$REPORT"
else
    echo "  Cannot compute statistics - log file missing" >> "$REPORT"
fi

separator

echo ""
echo "----------------------------------------------------"
echo "|           Forensic Report Generated              |"
echo "----------------------------------------------------"
echo ""
echo "  Report saved to: ${REPORT}"
echo ""
echo "  View with:  cat ${REPORT}"
echo ""

# Also print to stdout
cat "$REPORT"
