#!/bin/sh
# =============================================================================
# Script Name: dnsbl_stats.sh
# Version: 1.1
# Author: Andreas Fleckl
# Description: This script processes the DNSBL blacklist log, generates reports
#              on IP addresses at different levels of granularity, and emails 
#              these reports. It includes error handling and logging.
# =============================================================================

# Email address for the reports
EMAILADDRESS="your-email@example.com"

# Log file path
LOG_FILE="/var/log/dnsbl-ipset/blacklist.log"

# Temporary file for logging script actions
TEMP_LOG="/tmp/dnsbl-stats.log"

# Function to log messages
log_message() {
    echo "$(date +"%Y-%m-%d %H:%M:%S") - $1" | tee -a "$TEMP_LOG"
}

# Check if the log file exists
if [ ! -f "$LOG_FILE" ]; then
    log_message "Log file not found: $LOG_FILE"
    exit 1
fi

# Generate and email the reports
log_message "Generating and emailing reports..."
{
    cat "$LOG_FILE" | cut -d ' ' -f1 | sort | uniq -c | sort -nr | mail -s "dnsbl blacklist.log 32 weekly Report $(date)" "$EMAILADDRESS"
    cat "$LOG_FILE" | cut -d ' ' -f1 | awk -F\. '{print $1"."$2"."$3"."}' | sort | uniq -c | sort -nr | mail -s "dnsbl blacklist.log 24 weekly Report $(date)" "$EMAILADDRESS"
    cat "$LOG_FILE" | cut -d ' ' -f1 | awk -F\. '{print $1"."$2"."}' | sort | uniq -c | sort -nr | mail -s "dnsbl blacklist.log 16 weekly Report $(date)" "$EMAILADDRESS"
} && log_message "Reports emailed successfully." || log_message "Failed to email reports."

# Remove the log file
log_message "Removing log file..."
if rm "$LOG_FILE"; then
    log_message "Log file removed: $LOG_FILE"
else
    log_message "Failed to remove log file: $LOG_FILE"
    exit 1
fi

# Print the log to standard output and remove the temporary log file
cat "$TEMP_LOG"
rm "$TEMP_LOG"