#!/bin/bash

################################################################################
# Mail Queue Inspector
################################################################################
# Purpose: View and analyze mail queue
# Supports: Exim, Postfix, Sendmail
################################################################################

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
source "$SCRIPT_DIR/lib/common-functions.sh"
source "$SCRIPT_DIR/lib/system-detect.sh"
source "$SCRIPT_DIR/lib/system-variables.sh"
source "$SCRIPT_DIR/lib/email-functions.sh"

show_banner "Mail Queue Inspector"

# Detect MTA
MTA=$(detect_mta)

if [ "$MTA" = "unknown" ]; then
    print_error "No supported mail server (Exim/Postfix/Sendmail) detected"
    exit 1
fi

print_info "Detected mail server: $MTA"
echo ""

# Validate mail command variables are available
if [ -z "$SYS_MAIL_CMD_QUEUE_COUNT" ]; then
    print_error "Mail queue commands not available for $MTA"
    exit 1
fi

# ============================================================================
# EXIM: Queue inspection with frozen message detection
# ============================================================================

if [ "$MTA" = "exim" ]; then
    print_header "Queue Summary"

    # Exim: exim -bpc returns just the number
    queue_count=$(eval "$SYS_MAIL_CMD_QUEUE_COUNT")

    if [ "$queue_count" -gt 0 ] 2>/dev/null; then
        print_warning "$queue_count messages in queue"
        echo ""

        # Cache queue list - single execution for all operations
        queue_list=$(eval "$SYS_MAIL_CMD_QUEUE_LIST")

        print_header "Recent Queue Messages (last 20)"
        echo "$queue_list" | head -20
        echo ""

        print_header "Frozen Messages"
        # Count only lines that START with [frozen] (actual frozen message markers)
        frozen=$(echo "$queue_list" | grep -c "^\[frozen\]" 2>/dev/null || true)
        if [ "$frozen" -gt 0 ]; then
            print_warning "$frozen frozen messages found"
            echo "$queue_list" | grep "^\[frozen\]" | head -10 || true
        else
            print_success "No frozen messages"
        fi
    else
        print_success "Mail queue is empty"
    fi

# ============================================================================
# POSTFIX: Queue inspection with suspended message detection
# ============================================================================

elif [ "$MTA" = "postfix" ]; then
    print_header "Queue Summary"

    # Postfix: mailq | tail -1 returns "-- N Kbytes in M Requests."
    queue_summary=$(eval "$SYS_MAIL_CMD_QUEUE_COUNT")
    print_info "$queue_summary"

    # Extract message count from summary line (last number is always message count)
    # Pattern: "-- 9616 Kbytes in 3 Requests." → Extract "3"
    msg_count=$(echo "$queue_summary" | grep -oE '[0-9]+' | tail -1 || true)
    echo ""

    if [ -z "$msg_count" ] || [ "$msg_count" -eq 0 ] 2>/dev/null; then
        print_success "Mail queue is empty"
    else
        print_warning "$msg_count messages in queue"
        echo ""

        # Cache queue list - single execution for all operations
        queue_list=$(eval "$SYS_MAIL_CMD_QUEUE_LIST")

        print_header "Queue Details (first 50)"
        echo "$queue_list" | head -50
        echo ""

        print_header "Suspended Messages"
        # Postfix shows suspension reasons in parentheses on next line
        suspended=$(echo "$queue_list" | grep -c "delivery temporarily suspended" 2>/dev/null || true)

        if [ "$suspended" -gt 0 ]; then
            print_warning "$suspended suspended messages found (delivery deferred)"
            # Show message ID and first line of suspension reason
            echo "$queue_list" | grep -B1 "delivery temporarily suspended" | head -20 || true
        else
            print_success "No suspended messages"
        fi
    fi

# ============================================================================
# SENDMAIL: Queue inspection with deferred message detection
# ============================================================================

elif [ "$MTA" = "sendmail" ]; then
    print_header "Queue Summary"

    # Sendmail: mailq | tail -1 returns "-- N Kbytes in M Requests."
    queue_summary=$(eval "$SYS_MAIL_CMD_QUEUE_COUNT")
    print_info "$queue_summary"

    # Extract message count from summary line (last number is always message count)
    # Pattern: "-- 9616 Kbytes in 3 Requests." → Extract "3"
    msg_count=$(echo "$queue_summary" | grep -oE '[0-9]+' | tail -1 || true)
    echo ""

    if [ -z "$msg_count" ] || [ "$msg_count" -eq 0 ] 2>/dev/null; then
        print_success "Mail queue is empty"
    else
        print_warning "$msg_count messages in queue"
        echo ""

        # Cache queue list - single execution for all operations
        queue_list=$(eval "$SYS_MAIL_CMD_QUEUE_LIST")

        print_header "Queue Details (first 50)"
        echo "$queue_list" | head -50
        echo ""

        print_header "Deferred Messages"
        # Sendmail shows deferral reasons in parentheses on continuation lines
        # Continuation lines start with whitespace and opening parenthesis
        deferred=$(echo "$queue_list" | grep -c "^[[:space:]]*(" 2>/dev/null || true)

        if [ "$deferred" -gt 0 ]; then
            print_warning "$deferred deferred messages found"
            # Show deferred message reasons (continuation lines starting with spaces and parenthesis)
            echo "$queue_list" | grep "^[[:space:]]*(" | head -20 || true
        else
            print_success "No deferred messages"
        fi
    fi
fi

# ============================================================================
# Provide MTA-specific help commands
# ============================================================================

echo ""
if [ "$MTA" = "exim" ]; then
    print_info "Use 'exim -Mvl <message_id>' to view message details"
    print_info "Use 'exim -Mrm <message_id>' to remove a message"
    print_info "Use 'exim -Mrm -j frozen' to remove all frozen messages"
elif [ "$MTA" = "postfix" ]; then
    print_info "Use 'postcat -q <message_id>' to view message details"
    print_info "Use 'postsuper -d <message_id>' to remove a message"
    print_info "Use 'postsuper -r <message_id>' to requeue a message"
elif [ "$MTA" = "sendmail" ]; then
    print_info "Use 'mailstat' to view queue statistics"
    print_info "Use 'rm /var/spool/mqueue/qf<message_id>' to remove a message"
    print_info "Use 'mailq -Ac' to force queue processing"
fi
echo ""

press_enter
