#!/bin/bash
# =============================================================================
# Script Name: f2b_status.sh
# Version: 1.6
# Description: This script retrieves and displays the status of all Fail2Ban
#              jails, including error handling and logging.
# =============================================================================

# Log file path
LOG_FILE="/var/log/fail2ban-status.log"

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

# Function to retrieve the list of jails
get_jail_list() {
    fail2ban-client status | grep 'Jail list:' | cut -d ":" -f2 | tr -d ',' | xargs
}

# Retrieve the list of jails
log_message "Retrieving the list of Fail2Ban jails..."
JAIL_LIST=$(get_jail_list)

# Check if any jails were found
if [ -z "$JAIL_LIST" ]; then
    log_message "No jails found."
    exit 1
fi

# Convert JAIL_LIST into an array
IFS=' ' read -r -a JAIL_ARRAY <<< "$JAIL_LIST"

# Iterate over each jail and display its status
for JAIL in "${JAIL_ARRAY[@]}"; do
    log_message "Retrieving status for jail: $JAIL"
    STATUS=$(fail2ban-client status "$JAIL" 2>&1)
    
    if echo "$STATUS" | grep -q "Sorry but the jail"; then
        log_message "Failed to retrieve status for jail: $JAIL. Error: $STATUS"
    else
        log_message "Status for jail $JAIL retrieved successfully."
        echo "Status for jail: $JAIL"
        echo "$STATUS"
        echo "----------------------------"
    fi
done

log_message "Fail2Ban status check completed."