#!/bin/bash
#
# Simple shell script to update GeoIP database files
#
# Project    : ipv6calc/GeoIP
# File       : GeoIP-update.sh
# Version    : $Id: bc74b4c21e377d7ecec68d0178502439175c0e5c $
# Copyright  : 2012-2020 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] [-s] [-L] [-G]
	-s		skip download
	-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
}

while getopts "sGLD:vh\?" opt; do
	case $opt in
	    s)
		skip_download=1
		;;
	    D)
		GEOIP_DAT_DIR=$OPTARG
		;;
	    v)
		verbose=1
		;;
	    L)
		echo "ERROR : legacy mode is no longer supported"
		exit 1
		;;
	    G)
		echo "NOTICE: 'geoipupdate' is default since legacy is no longer supported"
		;;
	    *)
		help
		exit 1
		;;
	esac
done

geoipupdate=1 # 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" != "1" ]; 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

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

	geoipupdate ${verbose:+-v} -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
