#!/bin/bash
echo $$
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
####################################################################
# - GeoCount, coprocess -
#
# Count attacks by country 
#
#-------------------------
REALPATH=`realpath $0`
WHERE=`dirname $REALPATH`
ME=`basename $REALPATH`
cd $WHERE
. ../../system.conf
. ../../watchermap.conf
. ../../common.conf
. ../../common.bashlib
. GeoTrack.conf		# listen to mother's voice
#-------------------------
ME=`basename $ME -cop`

# Make a compare string from $ZONES for 'grep -E ...' 
COUNTRIES=`awk '{print toupper($0)}' <<< $ZONES | tr ' ' '|'`
TABLE=`awk '{print tolower($0)}' <<< $ME`

#----------------- Main -----------------------
trace "Starting $0 alias $ME"
: echo "Me       : $ME"
: echo "Where    : $WHERE"
: echo "FiFo base: $FIFO_BASE"
: echo "Pipe     : $PIPE"
: echo "DB       : $DB"
: echo "Table    : $TABLE"

PROC_START=`date +%s`

#trap cleanup		0 1 2 9 15
trap stopit		TERM INT
trap 'leave $? "$_"'	EXIT

leave() {
local funtag="[${FUNCNAME[0]}]"
	trace "$funtag ERR Code: $1, Last CMD: $2"
	kill -9 $$
}

stopit() {
local funtag="[${FUNCNAME[0]}]"
	trace "$funtag Terminating on request ..."
	cleanup
}

cleanup() {
local funtag="[${FUNCNAME[0]}]"
	PROC_END=`date +%s`
	PROC_TIM=$(( PROC_END - PROC_START ))
	DAYS=$(( PROC_TIM / 86400 ))
	REST=$(( PROC_TIM % 86400 ))
	trace "$funtag Processing time: $DAYS days `date -ud @$REST +%T`"
	exit
}

trace "Starting scanner in $ME ..."
while :
do
	read
	((loop++))
	LOOP_START=`date +%s%3N`
	P1=`awk '{ print $1 }' <<< "$REPLY"`

	if [ -z "$P1" ]
	then	trace "No country code ...continuing ..."
		sleep 1; continue
	else	COUNTRY=$P1
	fi

	haveit=`$SQL "select country from $TABLE where country='$COUNTRY'";`

	if [ -z "$haveit" ]
	then
		$SQL "insert into $TABLE (country, count, lasttime) 
			values ('$COUNTRY',1,
				datetime(current_timestamp,'localtime')
			);"
	else
		$SQL "update $TABLE 
			set 	count    = count+1,
				lasttime = datetime(current_timestamp,'localtime')
			where country='$COUNTRY'
			;"
	fi

	LOOP_END=`date +%s%3N`
	LOOP_TIM=$(( LOOP_END - LOOP_START ))
	trace "$COUNTRY, Loop time: $LOOP_TIM""ms"
done

