#!/bin/bash

################################################################################
# SPF/DKIM/DMARC Check - Email Authentication Records Validator
################################################################################
# Purpose: Check and validate SPF, DKIM, and DMARC records for a domain
# Shows detailed validation results with recommendations
################################################################################

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

show_banner "SPF/DKIM/DMARC Email Authentication Check"

# Get domain from user
echo ""
read -p "Enter domain to check (e.g., example.com): " TARGET_DOMAIN

if [ -z "$TARGET_DOMAIN" ]; then
    print_error "Domain required"
    exit 1
fi

print_info "Checking email authentication records for: $TARGET_DOMAIN"
echo ""

################################################################################
# SPF Check
################################################################################

check_spf() {
    local domain="$1"
    local spf_record=$(dig +short TXT "$domain" 2>/dev/null | grep "^\"v=spf1")

    if [ -z "$spf_record" ]; then
        print_error "  ✗ SPF record NOT FOUND"
        echo "    Risk: Server may not have SPF authentication"
        return 1
    else
        print_success "  ✓ SPF record found"
        # Clean up the dig output
        spf_record=$(echo "$spf_record" | sed 's/"//g')
        echo "    Record: $spf_record"

        # Validate SPF record
        if echo "$spf_record" | grep -q "~all\|?all"; then
            print_success "    ✓ SPF has proper terminator (~all or ?all)"
        elif echo "$spf_record" | grep -q "\-all"; then
            print_warning "    ⚠ SPF uses strict -all (may reject legitimate mail)"
        else
            print_warning "    ⚠ SPF missing proper terminator (no ~all)"
        fi

        # Check for common SPF mechanisms
        echo "    Mechanisms found:"
        echo "$spf_record" | grep -o "\b[a-z]*:[^ \"]*" | while read mech; do
            echo "      • $mech"
        done

        return 0
    fi
}

################################################################################
# DKIM Check
################################################################################

check_dkim() {
    local domain="$1"
    local selector="default"

    # Try common selectors
    for sel in default k1 k2 google selector1 selector2; do
        local dkim_record=$(dig +short TXT "${sel}._domainkey.${domain}" 2>/dev/null | grep "^\"v=DKIM1")
        if [ -n "$dkim_record" ]; then
            selector="$sel"
            break
        fi
    done

    local dkim_record=$(dig +short TXT "${selector}._domainkey.${domain}" 2>/dev/null | grep "^\"v=DKIM1")

    if [ -z "$dkim_record" ]; then
        print_error "  ✗ DKIM record NOT FOUND (tried selector: $selector)"
        echo "    Recommendation: Check your DKIM setup with selector name"
        return 1
    else
        print_success "  ✓ DKIM record found (selector: $selector)"
        dkim_record=$(echo "$dkim_record" | sed 's/"//g')

        # Extract key components
        if echo "$dkim_record" | grep -q "p="; then
            print_success "    ✓ Public key (p=) present"
        fi

        if echo "$dkim_record" | grep -q "h=sha256"; then
            print_success "    ✓ Using SHA256 hashing (recommended)"
        elif echo "$dkim_record" | grep -q "h=sha1"; then
            print_warning "    ⚠ Using SHA1 (consider upgrading to SHA256)"
        fi

        if echo "$dkim_record" | grep -q "t=y"; then
            print_info "    ℹ Testing mode enabled (t=y)"
        fi

        echo "    Selector: $selector"
        return 0
    fi
}

################################################################################
# DMARC Check
################################################################################

check_dmarc() {
    local domain="$1"
    local dmarc_record=$(dig +short TXT "_dmarc.${domain}" 2>/dev/null | grep "^\"v=DMARC1")

    if [ -z "$dmarc_record" ]; then
        print_error "  ✗ DMARC record NOT FOUND"
        echo "    Recommendation: Implement DMARC policy for maximum protection"
        return 1
    else
        print_success "  ✓ DMARC record found"
        dmarc_record=$(echo "$dmarc_record" | sed 's/"//g')
        echo "    Record: $dmarc_record"

        # Analyze DMARC policy
        if echo "$dmarc_record" | grep -q "p=reject"; then
            print_success "    ✓ Policy: REJECT (strict enforcement)"
        elif echo "$dmarc_record" | grep -q "p=quarantine"; then
            print_warning "    ⚠ Policy: QUARANTINE (less strict)"
        elif echo "$dmarc_record" | grep -q "p=none"; then
            print_warning "    ⚠ Policy: NONE (monitoring only, no enforcement)"
        fi

        # Check for reporting
        if echo "$dmarc_record" | grep -q "rua="; then
            print_success "    ✓ Aggregate reports enabled (rua=)"
        fi

        if echo "$dmarc_record" | grep -q "ruf="; then
            print_success "    ✓ Forensic reports enabled (ruf=)"
        fi

        # Check alignment
        if echo "$dmarc_record" | grep -q "aspf=strict"; then
            print_success "    ✓ SPF alignment: STRICT"
        fi

        if echo "$dmarc_record" | grep -q "adkim=strict"; then
            print_success "    ✓ DKIM alignment: STRICT"
        fi

        return 0
    fi
}

################################################################################
# Main Checks
################################################################################

print_header "SPF (Sender Policy Framework)"
check_spf "$TARGET_DOMAIN"
spf_status=$?
echo ""

print_header "DKIM (DomainKeys Identified Mail)"
check_dkim "$TARGET_DOMAIN"
dkim_status=$?
echo ""

print_header "DMARC (Domain-based Message Authentication, Reporting & Conformance)"
check_dmarc "$TARGET_DOMAIN"
dmarc_status=$?
echo ""

################################################################################
# Summary & Recommendations
################################################################################

print_header "Authentication Summary"

echo ""
print_info "Status Overview:"

if [ "$spf_status" = 0 ]; then
    echo "  ✓ SPF: Implemented"
else
    echo "  ✗ SPF: Missing"
fi

if [ "$dkim_status" = 0 ]; then
    echo "  ✓ DKIM: Implemented"
else
    echo "  ✗ DKIM: Missing"
fi

if [ "$dmarc_status" = 0 ]; then
    echo "  ✓ DMARC: Implemented"
else
    echo "  ✗ DMARC: Missing"
fi

echo ""
echo "🔐 Authentication Strength:"

if [ "$spf_status" = 0 ] && [ "$dkim_status" = 0 ] && [ "$dmarc_status" = 0 ]; then
    print_success "  ✓ EXCELLENT: All three authentication methods implemented"
    echo "    Your domain has maximum email authentication protection"
elif [ "$spf_status" = 0 ] && [ "$dkim_status" = 0 ]; then
    print_warning "  ⚠ GOOD: SPF and DKIM implemented (DMARC recommended)"
    echo "    Add DMARC for complete protection and reporting"
elif [ "$spf_status" = 0 ] || [ "$dkim_status" = 0 ]; then
    print_warning "  ⚠ PARTIAL: Only one authentication method active"
    echo "    Implement both SPF and DKIM for better deliverability"
else
    print_error "  ✗ CRITICAL: No authentication methods found"
    echo "    Email deliverability will be severely impacted"
fi

echo ""
echo "📋 Recommendations:"
echo ""

if [ "$spf_status" != 0 ]; then
    echo "  1. Add SPF record:"
    echo "     - Go to your DNS provider"
    echo "     - Add TXT record for $TARGET_DOMAIN"
    echo "     - Example: v=spf1 include:_spf.google.com ~all"
    echo ""
fi

if [ "$dkim_status" != 0 ]; then
    echo "  2. Enable DKIM:"
    echo "     - Check your mail server control panel (cPanel/Plesk)"
    echo "     - Generate DKIM key for domain"
    echo "     - Add the TXT record to DNS"
    echo ""
fi

if [ "$dmarc_status" != 0 ]; then
    echo "  3. Implement DMARC:"
    echo "     - Add TXT record for _dmarc.$TARGET_DOMAIN"
    echo "     - Start with p=none for monitoring"
    echo "     - Example: v=DMARC1;p=none;rua=mailto:postmaster@$TARGET_DOMAIN"
    echo ""
fi

echo "🔗 Additional Resources:"
echo "  • Use email-diagnostics to check email delivery issues"
echo "  • Use blacklist-check to verify IP reputation"
echo "  • Monitor DMARC reports at your email provider"
echo ""
