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

GEOIP_DAT_DIR_DEFAULT="/usr/share/GeoIP"
[ -z "$GEOIP_DAT_DIR" ] && GEOIP_DAT_DIR="$GEOIP_DAT_DIR_DEFAULT"

GEOIP_DAT_URL_BASE="http://geolite.maxmind.com/download/geoip/database/"
GEOIP_DAT_FILES="GeoLiteCountry/GeoIP.dat.gz GeoIPv6.dat.gz GeoLiteCity.dat.gz GeoLiteCityv6-beta/GeoLiteCityv6.dat.gz asnum/GeoIPASNum.dat.gz asnum/GeoIPASNumv6.dat.gz"


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

	database directory: $GEOIP_DAT_DIR (default: $GEOIP_DAT_DIR_DEFAULT)

	it honors externally defined environment value: GEOIP_DAT_DIR

 this script will download data from geolite.maxmind.com (GeoIP)
 into given/set database directory

 GEOIP_DAT_URL_BASE=$GEOIP_DAT_URL_BASE
 GEOIP_DAT_FILES=$GEOIP_DAT_FILES
END
}

while getopts "D:h\?" opt; do
	case $opt in
	    D)
		GEOIP_DAT_DIR=$OPTARG
		;;
	    *)
		help
		exit 1
		;;
	esac
done


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

# Download and unpack files
for file in $GEOIP_DAT_FILES; do
	file_basename="`basename "$file"`"
	file_basename_decomp="`basename "$file" .gz`"
	file_dest="$GEOIP_DAT_DIR/$file_basename"

	echo "INFO  : try to download file: $file ($file_dest)"
	wget -q -O "$file_dest" "$GEOIP_DAT_URL_BASE$file"
	if [ $? -ne 0 ]; then
		echo "ERROR : download of file not successful: $file ($file_dest)"
		continue
	fi
	echo "INFO  : download of file successful: $file ($file_dest)"

	gunzip -f "$file_dest"
	if [ $? -ne 0 ]; then
		echo "ERROR : unzip of file not successful: $file_dest"
		continue
	fi
	echo "INFO  : unzip of file successful: $file_dest"

	# check for softlinks
	case "$file_basename_decomp" in
	    GeoLiteCity.dat)
		softlinkdst="GeoIPCity.dat" 
		;;
	    GeoLiteCityv6.dat)
		softlinkdst="GeoIPCityv6.dat" 
		;;
	    *)
		softlinkdst="" 
        esac

	if [ -n "$softlinkdst" -a ! -e "$GEOIP_DAT_DIR/$softlinkdst" ]; then
		echo "NOTICE: softlink missing, create: $softlinkdst"
		ln -s "$file_basename_decomp" "$GEOIP_DAT_DIR/$softlinkdst"
	fi
done
