#!/bin/bash
#
# Simple shell script to update GeoIP database files
#
# Project    : ipv6calc/GeoIP
# File       : GeoIP-update.sh
# Version    : $Id: 3a140243e56962310c377ade0a91273e308ab836 $
# Copyright  : 2012-2021 by Peter Bieringer <pb (at) bieringer.de>
# License    : GNU GPL version 2

GEOIP_DAT_DIR_DEFAULT="@GEOIP2_DB@"
[ -z "$GEOIP_DAT_DIR" -a -n "$IPV6CALC_DB_GEOIP2_DIR" ] && GEOIP_DAT_DIR="$IPV6CALC_DB_GEOIP2_DIR"
[ -z "$GEOIP_DAT_DIR" ] && GEOIP_DAT_DIR="$GEOIP_DAT_DIR_DEFAULT"

help() {
	cat <<END
Usage: $(basename "$0") [-D <dir>] [-v] [-L] [-G]
	-D <dir>	database directory (optional)
	-v		verbose

	database directory: $GEOIP_DAT_DIR (default: $GEOIP_DAT_DIR_DEFAULT)

	it honors externally defined environment value:
		prio 1: GEOIP_DAT_DIR
		prio 2: IPV6CALC_DB_GEOIP2_DIR

 adjust /etc/GeoIP.conf in advance:
   EditionIDs GeoLite2-Country GeoLite2-City GeoLite2-ASN
   (in case a valid license key exists, add key and extend EditionIDs related)
   see also https://dev.maxmind.com/geoip/geoipupdate/
END
}

verbose=
while getopts "sGLD:vh\?" opt; do
	case $opt in
	    s)	# for backward compatibility
		;;
	    D)
		GEOIP_DAT_DIR=$OPTARG
		;;
	    v)
		verbose=-v
		;;
	    L)
		echo "ERROR : legacy mode is no longer supported"
		exit 1
		;;
	    G)
		echo "NOTICE: 'geoipupdate' is default since legacy is no longer supported (dedicated option '-G' can be removed now)"
		;;
	    *)
		help
		exit 1
		;;
	esac
done

geoipupdate=true # now default, legacy is no longer working

if [ ! -d "$GEOIP_DAT_DIR" ]; then
	echo "ERROR : missing directory: $GEOIP_DAT_DIR"
	exit 1
fi

if [ ! -w "$GEOIP_DAT_DIR" ]; then
	echo "ERROR : missing write permissions on directory: $GEOIP_DAT_DIR"
	exit 1
fi

if [ ! -t 0 ]; then
	options_wget="-q"
fi


if ! $geoipupdate; then
	echo "ERROR : legacy mode is no longer supported (and this part of code should not be reached anymore...)"
	exit 1
else
	geoipupdate_bin=$(which geoipupdate)

	if [ -z "$geoipupdate_bin" ]; then
		echo "ERROR : missing binary 'geoipupdate' not found, can't continue"
		exit 1
	fi

	[ -n "$verbose" ] && echo "INFO  : call now: geoipupdate -v -d $GEOIP_DAT_DIR"

	geoipupdate $verbose -d $GEOIP_DAT_DIR
	if [ $? -ne 0 ]; then
		echo "ERROR : 'geoipupdate' stopped with error"
		exit 1
	fi
	echo "INFO  : 'geoipupdate' was successful"
fi # end of using geoipupdate
