#!/bin/bash
### Sample download script for https://mailfud.org/geoip-legacy/
### - Adjust DBDIR and FILES below
### - Copy script to /etc/cron.weekly or similar for your OS,
### note that /etc/cron.* filename MUST NOT HAVE .sh extension,
### rename to /etc/cron.weekly/geoip_update
### Contact: admin@mailfud.org
# Database directory
DBDIR=@DATABASES_DIR@
# Files to download (.dat.gz suffix not required)
# FILES="GeoIP GeoIPv6 GeoIPCity GeoIPCityv6 GeoIPASNum GeoIPASNumv6 GeoIPOrg GeoIPISP"
FILES="@DATABASES_LIST@"
# If http proxy needed
#https_proxy="http://foo.bar:3128"
### v0.24
### - add support for Ubuntu 22.04 /usr/libexec/xtables-addons/xt_geoip_build
### v0.23
### - fix xtables 3.8+, requires dbip-country-lite.csv
### v0.22
### - fix xtables stuff
### v0.21
### - added GeoIPCityv6, GeoIPASNumv6, fix https_proxy export
# DB directory
test -w $DBDIR && cd $DBDIR 2>/dev/null || { echo "Invalid directory: $DBDIR"; exit 1; }
# Sleep 0-600 sec if started from cron
if [ ! -t 0 ]; then sleep $((RANDOM/54)); fi
export https_proxy
for f in $FILES; do
# Make sure .gz is stripped
f=${f%*.gz}
# Make sure .dat exists
if [[ ! "$f" =~ \.csv ]]; then f=${f%*.dat}.dat; fi
# .gz files are kept on disk to compare timestamps (-N)
wget -nv -N -T 30 --max-redirect 0 https://mailfud.org/geoip-legacy/$f.gz
RET=$?
if [ $RET -ne 0 ]; then
echo "wget $f.gz failed: $RET" >&2
continue
fi
# Unpack and replace files atomically
if gzip -dc $f.gz >$f.tmp; then
if ! diff $f $f.tmp >/dev/null 2>&1; then
if [ "$f" = "$XTABLES" ]; then XUPD=1; fi
echo "updating $f"
chmod 644 $f.tmp
/bin/mv -f $f.tmp $f
else
echo "$f is up to date"
fi
else
echo "gunzip $f failed" >&2
rm -f $f.gz
fi
rm -f $f.tmp
done