Created
September 18, 2012 07:46
-
-
Save mattrobenolt/3741853 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env sh | |
INSTALL_DIR=`pwd`/maxmind | |
log() { | |
printf "\033[90m...\033[0m $@\n" | |
} | |
abort() { | |
printf "\033[31mError: $@\033[0m\n" && exit 1 | |
} | |
HOST="http://geolite.maxmind.com/download/geoip/database" | |
# MaxMind files | |
GEOIP_COUNTRY_DAT="GeoIP.dat" | |
GEOIP_COUNTRY="${HOST}/GeoLiteCountry/${GEOIP_COUNTRY_DAT}.gz" | |
GEOIP_CITY_DAT="GeoLiteCity.dat" | |
GEOIP_CITY="${HOST}/${GEOIP_CITY_DAT}.gz" | |
HTTP_HEAD= | |
which wget > /dev/null && HTTP_HEAD="wget -S --spider" | |
which curl > /dev/null && HTTP_HEAD="curl -Is" | |
test -z "$HTTP_HEAD" && abort "curl or wget required" | |
HTTP_GET= | |
which wget > /dev/null && HTTP_GET="wget -q -O-" | |
which curl > /dev/null && HTTP_GET="curl -s" | |
test -d $INSTALL_DIR || mkdir -p $INSTALL_DIR | |
download() { | |
log "downloading $2.gz" | |
$HTTP_GET $1 | gzip -d - > $INSTALL_DIR/$2 | |
} | |
# If the file needs downloaded, return 0 | |
# Else, return 1 | |
check_last_modified() { | |
# If the file doesn't exist at all, return 0 | |
test -f $INSTALL_DIR/$2 || return 0 | |
# Grab the HTTP headers | |
local headers="$( $HTTP_HEAD $1 2> /dev/null )" | |
# Strip out the Last-Modified header | |
local last_modified="$( \ | |
echo "$headers" \ | |
| grep -i 'last-modified' \ | |
| sed 's/[Ll]ast-[Mm]odified://g' )" | |
# Convert string format to epoch time | |
last_modified=`date -d "$last_modified" +%s` | |
# Modified time of existing file | |
local mtime=`stat -c %Y $INSTALL_DIR/$2` | |
# If the file on the remote server is newer, return 0 | |
test $last_modified -gt $mtime && return 0 | |
# We must have the latest file, return 1 | |
return 1 | |
} | |
check_last_modified $GEOIP_COUNTRY $GEOIP_COUNTRY_DAT \ | |
&& download $GEOIP_COUNTRY $GEOIP_COUNTRY_DAT | |
check_last_modified $GEOIP_CITY $GEOIP_CITY_DAT \ | |
&& download $GEOIP_CITY $GEOIP_CITY_DAT |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment