#!/bin/sh

# Input files (generated by blacklists_updater_txt.sh)
blacklist_file="blacklists/blacklist.txt"
blacklist_v4_file="blacklists/blacklist-v4.txt"
blacklist_v6_file="blacklists/blacklist-v6.txt"

# Output directory and files
nginx_output_dir="blacklists_nginx"
nginx_output_file="${nginx_output_dir}/blacklist.conf"
nginx_v4_output_file="${nginx_output_dir}/blacklist-v4.conf"
nginx_v6_output_file="${nginx_output_dir}/blacklist-v6.conf"

# Create nginx directory if it doesn't exist
mkdir -p "${nginx_output_dir}"

# Function to generate nginx config from input file
generate_nginx_config() {
    local input_file="$1"
    local output_file="$2"
    local ip_version="$3"

    # Generate nginx configuration with header
    cat > "${output_file}" << EOF
# Nginx blacklist configuration ${ip_version}
# Auto-generated from $(basename ${input_file})
# Last updated: $(date -u +"%Y-%m-%d %H:%M:%S UTC")
#
# Usage: Include this file in your nginx server or location block:
#   include /path/to/$(basename ${output_file});
#

EOF

    # Add deny directives for each network/IP
    while IFS= read -r network; do
        # Skip empty lines
        [ -z "${network}" ] && continue
        echo "deny ${network};" >> "${output_file}"
    done < "${input_file}"

    # Add final newline
    echo "" >> "${output_file}"

    echo "✓ Generated ${ip_version}: ${output_file}"
    echo "  Total entries: $(grep -c "deny" "${output_file}")"
}

# Generate nginx configurations from blacklist files
generate_nginx_config "${blacklist_file}" "${nginx_output_file}" "(mixed IPv4/IPv6)"
generate_nginx_config "${blacklist_v4_file}" "${nginx_v4_output_file}" "(IPv4 only)"
generate_nginx_config "${blacklist_v6_file}" "${nginx_v6_output_file}" "(IPv6 only)"
