#!/bin/bash
if [[ "$1" == 'debug'  ]]; then set -x;		_DEBUG=$1; shift; fi
if [[ "$1" == 'debug2' ]]; then set -xvT;	_DEBUG=$1; shift; fi
if [[ "$1" == 'trace'  ]]; then 		_TRACE=$1; shift; fi
####################################################################
####################################################
# - Blacklist, Master -
# Run this manually after changes 
# or from crontab with a short cycle; e.g. 5 minutes
####################################################
#------------------------
REALPATH=`realpath $0`
WHERE=`dirname $REALPATH`
ME=`basename $REALPATH`
cd $WHERE
. ../system.conf
. ../common.conf
. ../common.bashlib
#------------------------

if [ -f $MASTER_PATH/blacklist ]
then
	BLACK=`awk '
	BEGIN {}
	/^$/		{ next }	# Blank lines ignored
	/^[ \t]*[#]+/	{ next }	# Comment lines ignored	
			{ IPS[$1]=$1 }
	END { for (ip in IPS) { print ip } }
	' $MASTER_PATH/blacklist`

	logger	"$ME[$$] Black listing firewall ..."

	if ! ipset -q list blacklist >/dev/null 2>&1
	then
		ipset -exist create blacklist comment blacklisted
	fi

	ipset flush blacklist
	for w in `echo $BLACK`
	do 
		ipset -exist add blacklist $w comment blacklisted
	done

	logger	 "$ME[$$] Loaded blacklist from blacklist file ..."
else
	echo 	 "$ME: No backlist file ..."
fi
