#!/bin/bash
# Update geoip data
# The target file must be given as only argument on the commandline.
PATH=/bin:/usr/bin


# set the http proxy here:
# export http_proxy=http://proxy.example.com:8080/
# export HTTPS_PROXY=https://proxy.example.com:8080/
# export FTP_PROXY=ftp://proxy.example.com:8080/

# This product includes GeoLite2 data created by MaxMind, available from
# <a href="http://www.maxmind.com">http://www.maxmind.com</a>.

# requires a license key
# https://blog.maxmind.com/2019/12/18/significant-changes-to-accessing-and-using-geolite2-databases/

set -e
trap cleanup EXIT

fail()
{
  echo >&2 -e "$@"
  exit 23
}

setup()
{
  [ "$#" -eq 2 ] || fail "Exactly two arguments must be given:\n * DESTINATION-FILE (with absolute path, mmdb format)\n * GEOIP-LICENSE (See https://blog.maxmind.com/2019/12/18/significant-changes-to-accessing-and-using-geolite2-databases/ for details.)"
  DEST_FILE="$1"
  GEOIP_LICENSE="$2"
  TMP_DIR=`mktemp -d`
  dest_dir=`dirname "$DEST_FILE"`
  [ -d "$dest_dir" ] || mkdir -p "$dest_dir"
}

cleanup()
{
  [ -d "$dest_dir" ] && rm -rf "$TMP_DIR"
}

fetch_and_install()
{
  cd "$TMP_DIR"
  curl -s -S -o GeoLite2-City.mmdb.tar.gz "https://download.maxmind.com/app/geoip_download?edition_id=GeoLite2-City&suffix=tar.gz&license_key=$GEOIP_LICENSE"
  tar -mzxf GeoLite2-City.mmdb.tar.gz
  mv -f GeoLite2-City_*/GeoLite2-City.mmdb "$DEST_FILE"
}

setup "$@"
fetch_and_install
