#!/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
####################################################################
# - LGinjector -
# Inject an immediate manual DROP into the database & firewall ...
#
# We get:
# $1	... IP address
# $2	... optional tag
#
#--------------------------
REALPATH=`realpath $0`
WHERE=`dirname $REALPATH`
ME=`basename $REALPATH`
cd $WHERE
. ../../system.conf
. ../../watchermap.conf
. ../../common.conf
. ../../common.bashlib
#--------------------------
. ./WatchLG.conf

DBInject() {
local	comment="$2"
	CLASS=`get_class $1`
	$SQL "insert into $TABLE (affairs, IP,type,class,initiator,state,date_intro,date_event,comment)
              values ('99','$1','$THIS_TYPE','$CLASS','$ME','DROP',
			datetime(current_timestamp,'localtime'),
			datetime(current_timestamp,'localtime'),
			'$comment');"
}

IntoFW() {
local comment

	# See if that beast is already dropped
	#
	if $IPSET -q test $MYSET $1
	then return
	fi

	# OK - have an addr not yet dropped
	#
	comment="Manual inject,$2"
	DBInject "$1" "$comment"
	$IPSET add custody $1 comment "custody,$comment"
}


#------------ Main ---------------
if [ -z "$2" ]
then TAG="Manual"
else TAG="$2"
fi

if [ -z "$1" ]
then
	echo "Usage: $ME IP_addr tag"
else
	# User input !! Check plausibility
	# Is it a legal IP address?
	validate_IP $1
	if [ $? -ne 0 ]
	then 	echo "Illegal IP address '$1' ... exiting"
		exit
	fi

	IntoFW "$1" "$TAG"
fi
