#!/bin/bash

MININTERVAL=86400
WHOISINTERVAL=604800
FULLVACUUM=604800
sources="arin ripe apnic afrinic twnic jpnic"
# latnic can't be automated yet

function load_whois()
{
	local source=$1
	local last="$HOME/.last{$source}"
	
	if ! [ -f $last ]; then
		touch $last;
	fi

   	INTERVAL=$(($(date +%s) - $(stat -c %Y $last)))
        if [ $(($WHOISINTERVAL - $INTERVAL)) -lt 0 ]; then
                date
                echo "$source load"
                /usr/local/sbin/pwhois-${source}-snapshot-load -r
                touch $last 
        else
                date
                echo No $source load this time
        fi
}



if [ ! -f $HOME/.lastrun ]; then
	touch $HOME/.lastrun
fi

if [ ! -f $HOME/.lastfullvacuum ]; then
	touch $HOME/.lastfullvacuum
fi


while true; do
	INTERVAL=$(($(date +%s) - $(stat -c %Y $HOME/.lastrun)))
	if [ $(($MININTERVAL - $INTERVAL)) -lt 0 ]; then
		SLEEP=1
	else
		SLEEP=$(($MININTERVAL - $INTERVAL))
	fi

	date
	echo Sleeping for $SLEEP seconds

	sleep $SLEEP
	touch $HOME/.lastrun

	date
	echo Snapshot load
	/usr/local/sbin/pwhois-snapshot-load

	# load the whois data based upon the schedule of 
	# marked last files which will be stated
	for s in sources ; do
		load_whois s
	done

	echo pwhoisd reload
	#/etc/init.d/pwhoisd reload
	kill -1 `cat /var/run/pwhoisd.pid`

	date
	echo Sleep 1 hour
	sleep 3600

	INTERVAL=$(($(date +%s) - $(stat -c %Y $HOME/.lastfullvacuum)))
	if [ $(($FULLVACUUM - $INTERVAL)) -lt 0 ]; then
		date
		echo Vacuuming full
		/usr/local/pgsql/bin/vacuumdb -a -v -z -f
		touch $HOME/.lastfullvacuum
	else
		date
		echo Vacuuming
		/usr/local/pgsql/bin/vacuumdb -a -v
	fi
done
	
