#!/bin/bash
# {{ ansible_managed }}
set -e -o pipefail 

# Create temporary directory
WORKFOLDER=$(mktemp -d)
mkdir -p $WORKFOLDER
mkdir -p $WORKFOLDER/ip2loc/

# Download latest from db-ip.com
cd $WORKFOLDER
/usr/libexec/xtables-addons/xt_geoip_dl

# Download maxmind legacy csv and process
wget https://download.maxmind.com/app/geoip_download?edition_id=GeoLite2-Country-CSV&license_key={{ geoip_license_key }}&suffix=zip -O $WORKFOLDER/GeoLite2-Country-CSV.zip
unzip -d $WORKFOLDER -j $WORKFOLDER/GeoLite2-Country-CSV.zip
wget https://mailfud.org/geoip-legacy/GeoIP-legacy.csv.gz -O $WORKFOLDER/GeoIP-legacy.csv.gz
gunzip $WORKFOLDER/GeoIP-legacy.csv.gz
cat $WORKFOLDER/GeoIP-legacy.csv | tr -d '"' | cut -d, -f1,2,5 > $WORKFOLDER/GeoIP-legacy-processed.csv
rm $WORKFOLDER/GeoIP-legacy.csv

# Download latest from https://github.com/sapics/ip-location-db
wget -P $WORKFOLDER https://cdn.jsdelivr.net/npm/@ip-location-db/geo-whois-asn-country/geo-whois-asn-country-ipv4.csv
wget -P $WORKFOLDER https://cdn.jsdelivr.net/npm/@ip-location-db/geo-whois-asn-country/geo-whois-asn-country-ipv6.csv
wget -P $WORKFOLDER https://cdn.jsdelivr.net/npm/@ip-location-db/iptoasn-country/iptoasn-country-ipv4.csv
wget -P $WORKFOLDER https://cdn.jsdelivr.net/npm/@ip-location-db/iptoasn-country/iptoasn-country-ipv6.csv
wget -P $WORKFOLDER https://cdn.jsdelivr.net/npm/@ip-location-db/dbip-country/dbip-country-ipv4.csv
wget -P $WORKFOLDER https://cdn.jsdelivr.net/npm/@ip-location-db/dbip-country/dbip-country-ipv6.csv
wget -P $WORKFOLDER https://cdn.jsdelivr.net/npm/@ip-location-db/geolite2-country/geolite2-country-ipv4.csv
wget -P $WORKFOLDER https://cdn.jsdelivr.net/npm/@ip-location-db/geolite2-country/geolite2-country-ipv6.csv

# Combine all csv and remove duplicates
cd $WORKFOLDER
cat *.csv > geoip.csv
sort -u geoip.csv -o {{ xt_geoip_home }}/dbip-country-lite.csv

# Remove temp directory and update geoip xtables
rm -r $WORKFOLDER
/usr/libexec/xtables-addons/xt_geoip_build -D {{ xt_geoip_home }}/ -i {{ xt_geoip_home }}/xt_geoip_build
rm {{ xt_geoip_home }}/dbip-country-lite.csv
