#!/usr/bin/with-contenv bash

echo "Applying the maxmind mod..."

# create GeoIP2 folder symlink
mkdir -p \
    /config/geoip2db
if [[ -d /var/lib/libmaxminddb ]] && [[ ! -L /var/lib/libmaxminddb ]]; then
    rm -rf /var/lib/libmaxminddb
fi
if [[ ! -d /var/lib/libmaxminddb ]]; then
    ln -s /config/geoip2db /var/lib/libmaxminddb
fi
# check GeoIP2 database
if [[ -n "${MAXMINDDB_USER_ID}" ]]; then
    sed -i "s|.*MAXMINDDB_USER_ID.*|MAXMINDDB_USER_ID=\"${MAXMINDDB_USER_ID}\"|g" /etc/libmaxminddb.cron.conf
else
    echo "Starting with Alpine 3.20 rebase, MaxMindDB now requires setting the env var MAXMINDDB_USER_ID with your account's user id."
fi
if [[ -n "${MAXMINDDB_LICENSE_KEY}" ]]; then
    sed -i "s|.*MAXMINDDB_LICENSE_KEY.*|MAXMINDDB_LICENSE_KEY=\"${MAXMINDDB_LICENSE_KEY}\"|g" /etc/libmaxminddb.cron.conf
    if [[ ! -f /var/lib/libmaxminddb/GeoLite2-City.mmdb ]]; then
        echo "Downloading GeoIP2 City database."
        /etc/periodic/weekly/libmaxminddb
    fi
elif [[ -f /var/lib/libmaxminddb/GeoLite2-City.mmdb ]]; then
    echo -e "Currently using the user provided GeoLite2-City.mmdb.\nIf you want to enable weekly auto-updates of the database, retrieve a free license key from MaxMind,\nand add a new env variable \"MAXMINDDB_LICENSE_KEY\", set to your license key."
else
    echo -e "Starting 2019/12/30, GeoIP2 databases require personal license key to download. Please retrieve a free license key from MaxMind,\nand add a new env variable \"MAXMINDDB_LICENSE_KEY\", set to your license key."
fi

if [[ ! -f /config/nginx/maxmind.conf ]]; then
    cp /defaults/maxmind.conf /config/nginx/maxmind.conf
fi

echo "Applied the maxmind mod"
