#!/bin/bash

export INTERBASE_LOCK=/var/lock/firebird

ip=1.2.3.4
start='2010-11-22'
stop='2010-11-22'


fill_file_list()
{
    local dir=$1; shift
    echo "searching for files...in $dir"
    find "$dir" -type f -name '*.gdb' 
}


# Найдем САМЫЕ посещаемые ресурсы.
whog()
{
    local ip=$1; shift
    local list=$1; shift
    local cnt=`wc -l < $list`
    local i
    local prc sprc=0
    local sql=
    while read database; do
	cat "$database" > /dev/null
	echo "DECLARE EXTERNAL FUNCTION UF_STRING2IP CSTRING(20) RETURNS INTEGER FREE_IT ENTRY_POINT 'uf_string2ip' MODULE_NAME 'vpnudf.dll';" \
	    | isql "$database" &>/dev/null

	uid="${database%/*.gdb}"
	uid="${uid##*/}"
	echo "select 'UID=$uid, IP=$ip Count:', count(*) CNT, 'size:', sum(sz) SZ from stat where 
		(sip=uf_string2ip('$ip') or dip=uf_string2ip('$ip')) 
		and 
		(ts between '$start' and '$stop');" | isql "$database" | fgrep 'Count:'
	echo -n . >&2
	prc=$((i++*100/cnt))
	[ "$sprc" = "$prc" ] && continue
	echo
	sprc=$prc
	echo "$prc %" >&2
    done < "$list"
}

date=${start//-/}
date=${date:0:6}
[ -f ${date}_list.txt ] || fill_file_list "/var/dbstat/${date}" > ${date}_list.txt

echo "Looking up DB"
time whog "$ip" ${date}_list.txt > who_goes_to_$ip.txt

echo "sorting..."
sort -k4,4n who_goes_to_$ip.txt > who_goes_to_$ip.txt1 \
    && mv -f who_goes_to_$ip.txt1 who_goes_to_$ip.txt

