#!/bin/bash

# ip2clue downloader
# Author: Catalin(ux) M. BOIE
# Home: http://software77.net/

source /etc/ip2clue/download.conf
if [ "${iptocountry}" = "0" ]; then
	exit 0
fi

set -e

cd /var/cache/ip2clue

old_md5="IpToCountry.csv.md5"
new_md5="IpToCountry.csv.new.md5"
data_file="IpToCountry.csv.gz"

if [ -r "${data_file}" ]; then
	mtime=`stat --format="%Z" ${data_file}`
	next=$[${mtime} + ${iptocountry} * 24 * 3600]
else
	next=0
fi
echo "mtime=${mtime}, next=${next}, now=`date +%s`"
if [ "${next}" -ge "`date +%s`" ]; then
	# do not update yet
	exit 0
fi

# md5 of the file
wget "http://software77.net/geo-ip?DL=3" -O "${new_md5}"

# wait some random time...
sleep $[${RANDOM}%120]

download=1
if [ -r "${old_md5}" ]; then
	cmp "${new_md5}" "${old_md5}"
	if [ "${?}" = "0" ]; then
		download=0
	fi
fi

if [ "${download}" = "0" ]; then
	rm -f "${new_md5}"
	exit 0
fi

wget "http://software77.net/geo-ip?DL=1" -O "${data_file}"
mv "${new_md5}" "${old_md5}"
gzip -d "${data_file}"
