#!/bin/sh

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

# arguments:
# $1 URL
# $2 output file name
_fetch() {
    url="$1"
    out="$2"
    TEMPDIR="$(mktemp -d '/usr/local/share/GeoIP/GeoIPupdate.XXXXXX')"
    trap 'rc=$? ; set +e ; rm -rf "'"$TEMPDIR"'" ; exit $rc' 0
    if fetch -o "$TEMPDIR/$out.gz" "$url"; then
        gunzip "$TEMPDIR/$out.gz"
        chmod 444 "$TEMPDIR/$out"
        if ! mv -f "$TEMPDIR/$out" "/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
    rmdir "$TEMPDIR"
    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
