#!/bin/bash

GRN='\e[32m'
RED='\e[31m'
END='\e[0m'


if ! command -v ipset >/dev/null 2>&1; then
    echo -e "${RED}Error: 'ipset' command not found. Please install it first.${END}"
    exit 1
fi

echo ""
echo -e "You can check the country code here ${GRN}https://www.ipdeny.com/ipblocks/${END}"
echo ""

read -p "Please enter a comma-separated list of country-code you want to block: " input

echo ""
echo -e "${RED}Current network config: ${END}"
echo ""

ip a

echo ""
read -p "Please enter the interface on which you want to block all http(s) for the selected countries: " interface
echo ""

echo -e "${RED}Downloading and creating country zones ${END}"
echo ""

IFS=',' read -ra countries <<< "$input"

for country in "${countries[@]}"; do

	trimmed_country=$(echo "$country" |xargs)

	wget -q https://www.ipdeny.com/ipblocks/data/aggregated/$trimmed_country-aggregated.zone
	ipset -exist flush $trimmed_country
	ipset -exist create $trimmed_country hash:net
	for i in $(cat $trimmed_country-aggregated.zone); do ipset -q -A $trimmed_country $i; done

	listsize=$(( $(ipset list $trimmed_country | wc -l) - 8))

	if [[ ${listsize} == 0 ]]; then
		echo -e "${RED}The ipset $trimmed_country is empty, please check if something went wrong.${END}"
	else
		echo ""
		echo -e "+++ ${GRN}IPSET $trimmed_country added with ${listsize} entries${END} +++"
		echo -e "Add this rule in iptables to block the country:${RED} \"iptables -I INPUT -i ${interface} -p tcp  --match multiport --dports 80,443 -m set --match-set $trimmed_country src -j DROP\"${END}"
	echo ""
	fi
done

echo ""
echo    "=================================================="
echo -e " ${GRN}Some handy commands to verify the created sets: ${END}"
echo    "=================================================="
echo -e "Show a list of all ipset collections: ${RED}ipset list -n${END}"
echo -e "Show content of an ipset: ${RED}ipset list *setname*${END}"
echo -e "Match a known IP to a set: ${RED}ipset test *setname* *ip*${END}"
echo ""
