#!/bin/bash
#################################
Maxmind_Licensekey="ABCDEFGHIJKL"
#################################
CITYDATA="N" ### config - DISABLE city it'll be need free memory 2GB
### geoip set
GEOIPDIR="/usr/share/GeoIP"
DATALINK="/usr/share/xt_geoip /var/lib/GeoIP"
### avoid overlap
lockfile=/var/lock/$(basename $0)
if [ -f $lockfile ];then
P=$(cat $lockfile)
if [ -n "$(ps --no-headers -f $P)" ];then
exit 1
fi
fi
echo $$ > $lockfile
trap 'rm -f "$lockfile"' EXIT
### define server are primary or secandary.
### install dependances
if [[ -z $(which git) ]];then sudo yum -y install git > /dev/null 2>&1 ;fi
if [[ -z $(which pip) ]];then sudo yum -y install python2-pip > /dev/null 2>&1;fi
if [[ -z $(pip list|grep pygeoip) ]];then sudo pip install pygeoip > /dev/null 2>&1 ;fi
if [[ -z $(pip list|grep ipaddr) ]];then sudo pip install ipaddr > /dev/null 2>&1 ;fi
### link path
if [[ ! -d $GEOIPDIR ]];then
mkdir -p $GEOIPDIR
fi
for a in $DATALINK
do
if [[ ! -d $a ]];then if [[ $(readlink $a) != $GEOIPDIR ]];then
rm -rf $a;ln -s $GEOIPDIR $a
fi;fi
done
### https://github.com/sherpya/geolite2legacy - csv to data file.
cd $GEOIPDIR
if [ ! -e $GEOIPDIR/geolite2legacy/geolite2legacy.py ];then cd $GEOIPDIR
git clone https://github.com/sherpya/geolite2legacy.git
fi
### make GeoIP.dat files from GeoLite2 CSV file.
if [ -d $GEOIPDIR/geolite2legacy ];then
cd $GEOIPDIR/geolite2legacy
EXT="zip"
CIF="GeoLite2-City-CSV"
COF="GeoLite2-Country-CSV"
BASEURL="https://download.maxmind.com/app/geoip_download?edition_id"
COF_URL="$BASEURL=$COF&license_key=$Maxmind_Licensekey&suffix=$EXT"
ORI_DATE=$(date +"%Y%m%d%H%M.%S" -d "$(curl -sI $COF_URL|grep ^Last-Modified:|cut -d, -f2)")
CSV_DATE=$(date +"%Y%m%d%H%M.%S" -d "$(stat -c %y $COF.$EXT)")
if [[ "$ORI_DATE" != "$CSV_DATE" ]];then
rm -f $COF.$EXT $CIF.$EXT
wget "$COF_URL" -O $COF.$EXT >/dev/null 2>&1
if [ -s $GEOIPDIR/geolite2legacy/$COF.$EXT ];then
python geolite2legacy.py --input-file $COF.$EXT --fips-file geoname2fips.csv --output-file GeoIP.dat
python geolite2legacy.py --input-file $COF.$EXT -6 --fips-file geoname2fips.csv --output-file GeoIPv6.dat
fi
if [[ $CITYDATA == "Y" ]];then
CIF_URL="$BASEURL=$CIF&license_key=$Maxmind_Licensekey&suffix=$EXT"
wget "$CIF_URL" -O $CIF.$EXT >/dev/null 2>&1
python geolite2legacy.py --input-file $CIF.$EXT --fips-file geoname2fips.csv --output-file GeoLiteCity.dat
python geolite2legacy.py --input-file $CIF.$EXT -6 --fips-file geoname2fips.csv --output-file GeoLiteCityv6.dat
touch -t $ORI_DATE GeoLiteCity.dat GeoLiteCityv6.dat
mv -f Geo{LiteCity,LiteCityv6}.dat $GEOIPDIR/ >/dev/null 2>&1
fi
touch -t $ORI_DATE GeoIP.dat GeoIPv6.dat $COF.$EXT
mv -f Geo{IP,IPv6}.dat $GEOIPDIR/ >/dev/null 2>&1
fi
fi
exit 0