#!/bin/bash

# ip2clue downloader
# Author: Catalin(ux) M. BOIE
# Home: http://ip-to-country.webhosting.info/
# TODO: Use ETag to not download again the data!

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

set -e

cd /var/cache/ip2clue

data_file="ip-to-country.csv.zip"

if [ -r "${data_file}" ]; then
	mtime=`stat --format="%Z" ${data_file}`
	next=$[${mtime} + ${ip_to_location} * 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

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

wget "http://ip-to-country.webhosting.info/downloads/ip-to-country.csv.zip" -O "${data_file}"
unzip "${data_file}" 1>/dev/null
rm -f "${data_file}"
