#!/bin/bash
# ---------------------------------------------------------------   
#  check-logs.sh - Show authentication results from mail logs
# ---------------------------------------------------------------
#
#  Run from receiver-mta:
#    docker compose exec receiver-mta bash /scripts/check-logs.sh
# ---------------------------------------------------------------

LOGFILE="/var/log/mail.log"

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BOLD='\033[1m'
NC='\033[0m'

echo ""
echo -e "${BOLD}----------------------------------------------------${NC}"
echo -e "${BOLD}|          Mail Authentication Log Viewer          |${NC}"
echo -e "${BOLD}----------------------------------------------------${NC}"

if [ ! -f "$LOGFILE" ]; then
    echo -e "${RED}[!] Log file not found: ${LOGFILE}${NC}"
    exit 1
fi

# -- SPF results --
echo ""
echo -e "${BOLD}---- SPF Results ----${NC}"
grep -i "policyd-spf\|Received-SPF" "$LOGFILE" 2>/dev/null | tail -20 | \
    sed "s/Pass/${GREEN}Pass${NC}/gI; s/Fail/${RED}Fail${NC}/gI; s/None/${YELLOW}None${NC}/gI" || \
    echo "  (no SPF entries found)"

# -- DKIM results --
echo ""
echo -e "${BOLD}---- DKIM Results (OpenDKIM) ----${NC}"
grep -i "opendkim\|dkim" "$LOGFILE" 2>/dev/null | tail -20 | \
    sed "s/pass/${GREEN}pass${NC}/gI; s/fail/${RED}fail${NC}/gI; s/none/${YELLOW}none${NC}/gI" || \
    echo "  (no DKIM entries found)"

# -- DMARC results --
echo ""
echo -e "${BOLD}---- DMARC Results (OpenDMARC) ----${NC}"
grep -i "opendmarc\|dmarc" "$LOGFILE" 2>/dev/null | tail -20 | \
    sed "s/pass/${GREEN}pass${NC}/gI; s/fail/${RED}fail${NC}/gI; s/reject/${RED}reject${NC}/gI" || \
    echo "  (no DMARC entries found)"

# -- Postfix delivery status --
echo ""
echo -e "${BOLD}---- Postfix Delivery Status ----${NC}"
grep -i "status=\|reject\|550\|451" "$LOGFILE" 2>/dev/null | tail -20 | \
    sed "s/status=sent/${GREEN}status=sent${NC}/gI; s/status=delivered/${GREEN}status=delivered${NC}/gI; s/reject/${RED}reject${NC}/gI; s/550/${RED}550${NC}/gI" || \
    echo "  (no delivery status entries found)"

echo ""
