#!/usr/bin/env bash
# Refresh the DB-IP free country database (no account needed) and reload
# Caddy so the maxmind_geolocation matchers pick it up. Runs monthly via
# systemd timer as root (idle priority).
set -euo pipefail
DIR=/srv/paas/geoip
mkdir -p "$DIR"
tmp="$(mktemp -u)"
fetch() {
    curl -fsSL "https://download.db-ip.com/free/dbip-country-lite-$1.mmdb.gz" -o "$tmp.gz" \
        && gunzip -f "$tmp.gz" && [ -s "$tmp" ]
}
if fetch "$(date -u +%Y-%m)" || fetch "$(date -u -d '1 month ago' +%Y-%m)"; then
    install -m 644 "$tmp" "$DIR/country.mmdb"
    rm -f "$tmp"
    systemctl reload caddy 2>/dev/null || true
    echo "[geoip] refreshed $DIR/country.mmdb"
else
    rm -f "$tmp" "$tmp.gz" 2>/dev/null || true
    echo "[geoip] refresh failed — keeping existing database" >&2
    [ -f "$DIR/country.mmdb" ]   # exit non-zero only if we have no db at all
fi
