#!/bin/bash
# ---------------------------------------------------------------
#  check-headers.sh - Extract Authentication-Results from mailbox
# ---------------------------------------------------------------
#
#  Run from receiver-mta:
#    docker compose exec receiver-mta bash /scripts/check-headers.sh
# ---------------------------------------------------------------

MAILBOX="/var/mail/bob"

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

echo ""
echo -e "${BOLD}----------------------------------------------------${NC}"
echo -e "${BOLD}|        Authentication-Results Header Viewer      |${NC}"
echo -e "${BOLD}----------------------------------------------------${NC}"

if [ ! -f "$MAILBOX" ] || [ ! -s "$MAILBOX" ]; then
    echo ""
    echo -e "${YELLOW}[!] No mail in ${MAILBOX} - only delivered emails appear here.${NC}"
    echo -e "${YELLOW}    Rejected emails (Scenario B/C) will NOT have headers.${NC}"
    echo -e "${YELLOW}    Check logs instead:  bash /scripts/check-logs.sh${NC}"
    echo ""
    exit 0
fi

MSG_NUM=0

echo ""
echo -e "${CYAN}Reading mailbox: ${MAILBOX}${NC}"
echo ""

# Parse mbox format - each message starts with "From "
while IFS= read -r line; do
    if [[ "$line" =~ ^From\  ]]; then
        MSG_NUM=$((MSG_NUM + 1))
        IN_HEADERS=1
        echo -e "${BOLD}--- Message #${MSG_NUM} ---${NC}"
        echo ""
    fi

    if [ "$IN_HEADERS" = "1" ]; then
        # Empty line = end of headers
        if [ -z "$line" ]; then
            IN_HEADERS=0
            echo ""
            continue
        fi

        # Show key authentication and identity headers
        case "$line" in
            Authentication-Results:*|Received-SPF:*|DKIM-Signature:*)
                echo -e "${GREEN}${line}${NC}" | \
                    sed "s/pass/${GREEN}pass${NC}/gI; s/fail/${RED}fail${NC}/gI; s/none/${YELLOW}none${NC}/gI"
                ;;
            From:*|To:*|Subject:*|Date:*|Return-Path:*)
                echo -e "${CYAN}${line}${NC}"
                ;;
            # Show continuation lines (start with whitespace)
            [[:space:]]*)
                if [ "$SHOW_CONT" = "1" ]; then
                    echo -e "${GREEN}${line}${NC}" | \
                        sed "s/pass/${GREEN}pass${NC}/gI; s/fail/${RED}fail${NC}/gI; s/none/${YELLOW}none${NC}/gI"
                fi
                ;;
        esac

        # Track if we should show continuation lines
        case "$line" in
            Authentication-Results:*|Received-SPF:*|DKIM-Signature:*)
                SHOW_CONT=1
                ;;
            [[:space:]]*)
                ;;  # keep current state
            *)
                SHOW_CONT=0
                ;;
        esac
    fi
done < "$MAILBOX"

if [ "$MSG_NUM" = "0" ]; then
    echo -e "${YELLOW}No messages found in mailbox.${NC}"
fi

echo ""
