#!/bin/bash

BADGUYS_FILE=""  # The location (full path) where you want to download the list
CHAIN_NAME="CINSARMY_IPS"  # The firewall chain to hold the cinsarmy rules
FIREWALL="/sbin/iptables"  # The path to iptables
ETH=""  # The name of the ethernet port you'd like to apply these rules to. Example: eth1
BLOCKMODE=""  # If you want these rules to apply to just this machine, this should be "INPUT".
              # If you want these rules to apply to a network behind this machine, this should be "FORWARD".

# echo "Downloading the cinsarmy bad guys list of IPs."

wget -c https://cinsscore.com/list/ci-badguys.txt -q -O $BADGUYS_FILE

# Check if the file exists
if [[ ! -f "$BADGUYS_FILE" ]]; then
    echo "File not found: $BADGUYS_FILE"
    exit 1
fi

# echo "Making sure the file downloaded..."

# Check if the chain exists, and creates it if it's not there
if $FIREWALL -L $CHAIN_NAME -n &> /dev/null; then
    # echo "Chain $CHAIN_NAME already exists."
    $FIREWALL -F $CHAIN_NAME
else
    # echo "Creating chain $CHAIN_NAME."
    $FIREWALL -N $CHAIN_NAME
	# Jump to the our chain from the FORWARD CHAIN
	$FIREWALL -A $BLOCKMODE -j $CHAIN_NAME
fi

# echo "Processing the bad guys list..."

# Read each line (IP address) from the file and block it
while IFS= read -r ip; do
    # Check if the line is not empty
    if [[ -n "$ip" ]]; then
        # Block the IP address using $FIREWALL
        $FIREWALL -A $CHAIN_NAME -i $ETH -s "$ip" -j DROP
        # echo "Blocked IP: $ip"
    fi
done < "$BADGUYS_FILE"

# Delete the bad guys file
rm $BADGUYS_FILE

# echo "Bad guys list has been processed, and deleted."

# echo "Checking for return rule at the end of our chain."

# Check if the rule already exists

RETURNRULE="-A $CHAIN_NAME -p tcp -j RETURN"

if $FIREWALL -L $CHAIN_NAME -n | grep -q "tcp" && $FIREWALL -L $CHAIN_NAME -n | grep -q "RETURN"; then
    # echo "Rule already exists: $RETURNRULE"
    :
else
    # Add the rule if it doesn't exist
    $FIREWALL $RETURNRULE
    # echo "Rule added: $RETURNRULE"
fi

echo "Done."