#!/bin/sh

set -eu
echo Fetching GeoIP.dat and GeoIPv6.dat...

# arguments:
# $1 URL
# $2 output file name
_fetch() {
    url="$1"
    out="$2"
    TEMPFILE="$(mktemp "/usr/local/share/GeoIP"/GeoIP.dat-XXXXXX)"
    trap 'rc=$? ; set +e ; rm -f "'"$TEMPFILE"'" ; exit $rc' 0
    if fetch -o - "$url" | gunzip >> "$TEMPFILE" ; then
	chmod 444 "$TEMPFILE"
	if ! mv -f "$TEMPFILE" "/usr/local/share/GeoIP"/"$2" ; then
	    echo "Unable to replace /usr/local/share/GeoIP/$2"
	    return 2
	fi
    else
	echo "$2 download failed"
	return 1
    fi
    rm -f "$TEMPFILE"
    trap - 0
    return 0
}

_fetch "http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz" GeoIP.dat

_fetch "http://geolite.maxmind.com/download/geoip/database/GeoIPv6.dat.gz" GeoIPv6.dat
