#!/bin/bash

################################################################################
# IP Blacklist Checker
################################################################################
# Purpose: Check if server IP is blacklisted
################################################################################

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

show_banner "IP Blacklist Checker"

# Get server's public IP
print_info "Detecting server IP address..."
SERVER_IP=$(curl -s --max-time 5 ifconfig.me || curl -s --max-time 5 icanhazip.com || curl -s --max-time 5 ipecho.net/plain)

if [ -z "$SERVER_IP" ]; then
    print_error "Could not detect server IP address"
    exit 1
fi

print_success "Server IP: $SERVER_IP"
echo ""

# Blacklist database with difficulty ratings and removal URLs
# Format: "rbl_host|display_name|removal_url|difficulty|estimated_time"
BLACKLISTS_DB=(
    "zen.spamhaus.org|Spamhaus (ZEN)|https://check.spamhaus.org/|HARD|1-7 days"
    "bl.spamcop.net|SpamCop RBL|https://www.spamcop.net/bl.shtml|EASY|Same day"
    "bl.barracudacentral.org|Barracuda|https://www.barracudacentral.org/rbl/removal-request|MODERATE|1-3 days"
    "dnsbl.sorbs.net|SORBS|http://www.sorbs.net/lookup.shtml|MODERATE|1-2 days"
    "cbl.abuseat.org|CBL (Composite Block List)|https://cbl.abuseat.org/lookup.cgi|MODERATE|1-3 days"
    "psbl.surriel.com|PSBL|https://psbl.org/|MODERATE|1-2 days"
    "dnsbl-1.uceprotect.net|UCEPROTECT|http://www.uceprotect.net/en/rblcheck.php|HARD|3-7 days"
)

print_header "Checking Blacklists"
echo ""

LISTED=0
NOT_LISTED=0

# Reverse IP once for all lookups
REVERSED_IP=$(echo $SERVER_IP | awk -F. '{print $4"."$3"."$2"."$1}')

for entry in "${BLACKLISTS_DB[@]}"; do
    IFS='|' read -r rbl_host bl_name removal_url difficulty time_estimate <<< "$entry"

    # Check if listed (using dig with timeout for consistency)
    if dig +short +timeout=2 "$REVERSED_IP.$rbl_host" A 2>/dev/null | grep -q .; then
        print_error "✗ LISTED on $bl_name [$difficulty - $time_estimate]"
        echo "  Removal: $removal_url"
        ((LISTED++))
    else
        print_success "✓ Not listed on $bl_name"
        ((NOT_LISTED++))
    fi
done

echo ""
print_header "Summary"

if [ "$LISTED" -eq 0 ]; then
    print_success "✓ Server IP is clean ($NOT_LISTED blacklists checked)"
    echo "  Your server is not currently listed on any major blacklists."
else
    print_warning "⚠ Server IP is listed on $LISTED blacklist(s)"
    echo ""
    print_info "Delisting Difficulty Breakdown:"
    echo "  EASY (Same day): Check removal links above - usually automatic"
    echo "  MODERATE (1-3 days): Submit formal request, typically responsive"
    echo "  HARD (3-7+ days): Complex process, may require documentation"
    echo ""
    print_info "To delist your IP:"
    echo "  1. Review the removal URLs shown above for each listing"
    echo "  2. Identify and fix the underlying issue:"
    echo "     - Check for security compromises or spam accounts"
    echo "     - Verify SPF/DKIM/DMARC are correctly configured"
    echo "     - Review mail queue for suspicious content"
    echo "  3. Submit delisting request with justification"
    echo "  4. Track status using blacklist-check.sh regularly"
    echo ""
    print_info "Additional resources:"
    echo "  - Use 'email-diagnostics' for detailed analysis"
    echo "  - Check ~/email-diagnostics-history.json for patterns"
fi

echo ""
