#!/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
####################################################################
#
# - FillFW - (IPSETs)
# Have a loadfile created by each module or dynloader
# and load the firewall from this information
#
#------------------------
REALPATH=`realpath $0`
WHERE=`dirname $REALPATH`
ME=`basename $REALPATH`
cd $WHERE
. system.conf
. common.conf
. common.bashlib
#------------------------

logger "$ME[$$]: Started (re)loading firewall ..."

#
# Load IPSET information from dynloaders, modules and internal lists
#
. loader.conf

#
# Establish link with internal ipset DROP lists
# Modules & Dynloaders do this 'on the fly'
# NOTE: mk-ipset always creates DROP set
# !!! Don't use for the whitelist !!!
mk-ipset tarpit    'hash:ip'	'comment counters timeout 60'
mk-ipset custody   'hash:net'	'comment counters'
mk-ipset hijackers 'hash:net'	'comment counters'
mk-ipset Untreated 'hash:net'	'comment counters timeout 21600'

# Create runtime ipsets linked to 'raw/mangle PREROUTING'
mk-ipset_lowlevel custody-low   'hash:net'	'comment counters'
mk-ipset_lowlevel tarpit-low    'hash:ip'	'comment counters timeout 60'


###
# Special ACCEPT IPSETs ...
###
# Establish link with ipset 'passthru'
# THIS MUST COME LAST to go on top in iptables as 'ACCEPT'!!!)
#
ipset -exist create passthru 'hash:net' 'comment' 'counters'
if ! $IPTABLES -nL INPUT | grep "match-set passthru" | grep -q ACCEPT
then
        $IPTABLES -t filter -I INPUT    -m set --match-set passthru src -j ACCEPT
        $IPTABLES -t filter -I FORWARD  -m set --match-set passthru src -j ACCEPT
else	: echo "IPSET 'passthru' already established ... skipping"
fi

### Moved to function mk_myrouters() in common.bashlib
### # Establish link with ipset 'myrouters'
### # THIS MUST COME LAST to go on top in iptables as 'ACCEPT'!!!)
### #
### ipset -exist create myrouters 'hash:net' 'comment' 'counters'
### if ! $IPTABLES -t raw -nL PREROUTING | grep "match-set myrouters" | grep -q ACCEPT
### then
###         $IPTABLES -t raw    -I PREROUTING -m set --match-set myrouters src -j ACCEPT
###         $IPTABLES -t mangle -I PREROUTING -m set --match-set myrouters src -j ACCEPT
### else	: echo "IPSET 'myrouters' already established ... skipping"
### fi


# A dummy IPSET for validation of IP addresses (needed for DEBIAN/UBUNTU)
# Establish a dummy ipset just for ip addr validation
#
# --- DON'T CONNECT THIS WITH IPTABLES! ---

# Just 'add' and verify the return code 
ipset -exist create validate 'hash:net' comment timeout 1

logger "$ME[$$]: Finished - Firewall (re)loaded"
