#!/bin/bash
#
# ::copy::
# ::maintainter::
#
CMD=$(basename $0)
CMDVER="1.0"
CMDSTR="$CMD v.$CMDVER (2019/07)"

set -e -u


usage()
{
	echo "
=== $CMDSTR == GeoLite database update ===

usage: $CMD [-v]
" >&2
	show_settings >&2
	exit 1
}

show_settings()
{
	echo "
download url:    $GEOIP_URL

  country file:  $Country
  country ipv6:  $Country6
  city file:     $City
  ASN file:      $AsNum
"
}

to_syslog()
{
	while read line
	do
		line=$(echo "$line" | sed -e 's/^X//')
		if $VERBOSE
		then
			echo "$(date '+%Y%m%d-%H%M%S') $CMD $line"
		else
			logger -t $CMD -- "$line"
		fi
	done
	return 0
}




# (MAIN)

GEOIP_URL="http://geolite.maxmind.com/download/geoip/database/"

GeoLite2-Country.tar.gz
GeoLite2-City.tar.gz
GeoLite2-ASN.tar.gz
GEOIP_URL="https://geolite.maxmind.com/download/geoip/database"

Country="GeoLiteCountry/GeoIP.dat.gz"
City="GeoLiteCity.dat.gz"
AsNum="asnum/GeoIPASNum.dat.gz"

GEOIP_DIR="/usr/share/GeoIP"
WGET_PARMS="-t3 -T15"


# overrides defaults?
#
[ -s /etc/$CMD.conf ] && . /etc/$CMD.conf

VERBOSE=false

case ${1:-} in
  -v|--verbose)	VERBOSE=true; shift ;;
  -*)		usage ;;
esac

[ $# != 0 ] && usage


stat=0
out=

for file in $Country $Country6 $City $AsNum
do
	url="$GEOIP_URL/$file"
	file=$(basename "$file")

	tmpout=$(wget $WGET_PARMS -O "/tmp/$file" "$url" 2>&1) || {
		stat=$?
		out="$out\n$tmpout"
		continue
	}

	gunzip "/tmp/$file" || {
		stat=$?
		out="$out\n$tmpout"
		continue
	}

	file=$(basename "$file" .gz)

    	mv "/tmp/$file" "$GEOIP_DIR/$file"
done

if [ $stat = 0 ]
then
	echo "database updated" | to_syslog
else
	echo -e "ERROR $stat during database update:\n$out" | to_syslog
fi

exit $stat
