#!/bin/bash
# =============================================================================
# Script Name: ipset_blacklist_reload.sh
# Version: 1.1
# Author: Andreas Fleckl
# Description: This script reloads an ipset with CIDR /24 network ranges from a 
#              specified file, including error handling and logging.
# =============================================================================

# Define your ipset name
IPSET_NAME="blacklist"

# Path to your list of IP network ranges, one per line
IP_LIST_PATH="/etc/firehol/blacklist.netset"

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

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

# Function to check if a string is a CIDR network range specifically for /24
is_cidr_24() {
    local CIDR=$1
    if [[ $CIDR =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/24$ ]]; then
        return 0 # True
    else
        return 1 # False
    fi
}

# Clear the existing ipset
log_message "Flushing existing ipset: $IPSET_NAME"
if ipset flush "$IPSET_NAME"; then
    log_message "Successfully flushed ipset: $IPSET_NAME"
else
    log_message "Failed to flush ipset: $IPSET_NAME"
    exit 1
fi

# Repopulate the ipset
log_message "Repopulating ipset: $IPSET_NAME from file: $IP_LIST_PATH"
while IFS= read -r LINE; do
    # Skip empty lines and lines starting with #
    [[ -z "$LINE" ]] || [[ "$LINE" =~ ^# ]] && continue
    
    if is_cidr_24 "$LINE"; then
        # It's a CIDR /24 network range, add to blacklist
        if ipset add "$IPSET_NAME" "$LINE" 2>/dev/null; then
            log_message "Added $LINE to ipset: $IPSET_NAME"
        else
            log_message "Failed to add $LINE to ipset: $IPSET_NAME"
        fi
    else
        log_message "Skipping unrecognized format: $LINE"
    fi
done < "$IP_LIST_PATH"

log_message "Ipset $IPSET_NAME reloaded with networks from $IP_LIST_PATH"