#!/bin/sh
PREFIX=$(expr $0 : "\(/.*\)/bin/$(basename $0)\$") || exit 1

if [ -r $PREFIX/etc/utcount.conf ]; then
	. $PREFIX/etc/utcount.conf
else
	exit 1
fi

bindir=$PREFIX/bin
gate_connect=$bindir/$gate_connect
export gate_count_startnum

if [ -f /var/run/count.pid ] && ps `cat /var/run/count.pid` >/dev/null 2>&1
then
	echo "Another count process already run. Stop it and try again." >&2
	exit 1
fi

trap : 1
trap : 2
trap : 15
set -T
trap "rm -f /var/run/count.pid; exit" 1 2 15

echo -n $$ > /var/run/count.pid || exit 1

$gate_connect | while read action username address
do
	if echo "$action $username $address" \
		| grep -E -v -q "^[+-] [a-z].* ([0-9]{1,3}\.){3}[0-9]{1,3}$"
	then
		continue
	fi
	usernum=`$bindir/count_$gate_count_prog $action $username`
	$bindir/count_$gate_count_fw $action $usernum $address
	echo "[`date '+%d.%m.%y %H:%M'`] $action $username $address $usernum" \
		>> $gate_logfile
done
