#!/bin/bash

LOCKFILE=/var/lock/box-cronjob-maxminddb.lock

# the lockfile is not meant to be perfect, it's just in case the
# two cron scripts get run close to each other to keep
# them from stepping on each other's toes.

[ -f $LOCKFILE ] && exit 0
trap "{ rm -f $LOCKFILE ; exit 255; }" EXIT
touch $LOCKFILE

WGET_HASCONFIG="false"
if [ -f /etc/update-geoip-database.conf ]; then
    WGET_CONFIG="/etc/update-geoip-database.conf"
    WGET_HASCONFIG="true"
fi

if [ -f /etc/mmdb-database-update.conf ]; then
    WGET_CONFIG="/etc/mmdb-database-update.conf"
    WGET_HASCONFIG="true"
fi

function updateMaxMindDB
{
  if [ "$WGET_HASCONFIG" = "true" ]; then
    wget --config=$WGET_CONFIG --output-document=/tmp/maxminddb/GeoLite2-$1.tar.gz --quiet https://data.mageprofis.de/mmdb/GeoLite2-$1.tar.gz
  else
    wget --output-document=/tmp/maxminddb/GeoLite2-$1.tar.gz --quiet https://data.mageprofis.de/mmdb/GeoLite2-$1.tar.gz
  fi

  tar --wildcards --directory=/usr/share/GeoIP2/ --no-xattrs --no-selinux --no-acls --strip-components=1 -xf /tmp/maxminddb/GeoLite2-$1.tar.gz */GeoLite2-$1.mmdb

  mkdir -p /usr/share/GeoIP2/

  chown root:root /usr/share/GeoIP2/GeoLite2-$1.mmdb
}

mkdir /tmp/maxminddb

updateMaxMindDB ASN
updateMaxMindDB City
updateMaxMindDB Country

rm -rf /tmp/maxminddb

exit 0
