#!/bin/bash

# Guy Bruneau
# Date: 22 July 2022
# Filename: process_geoip.sh

# Source code put in public domain by Guy Bruneau, no Copyright
# Use at your own risk

# This software is provided "as is" without express or implied warranty or support

# https://installati.one/centos/7/libmaxminddb-devel/
# https://installati.one/centos/7/libmaxminddb-devel/

# This script is used to map IP address to their country code and ASN using Maxmind
# GeoIP files https://dev.maxmind.com/geoip?lang=en

# Removed old process data

/bin/rm ip_country.csv

# Get the filename to process

   echo -n "What is the filename to process? "
   read FILENAME


DOLLAR='$2'

array=(`cat $FILENAME | awk -F , "{ print $DOLLAR }" | sort | uniq`)

# Processing the list of IPs

i=1

for ((i=${#array[@]}; i>=0; i--)); do

  IP=${array[$i]}
  COUNTRY=`mmdblookup --file /usr/share/GeoIP/GeoLite2-Country.mmdb --ip $IP country iso_code` 
  ASN=`mmdblookup --file /usr/share/GeoIP/GeoLite2-ASN.mmdb --ip $IP autonomous_system_number`

  COUNTRY=`echo $COUNTRY | awk '{ print $1 }' | tr -d '"'`
  ASN=`echo $ASN | awk '{ print $1 }' | tr -d '"'`

  echo "$IP,$COUNTRY,$ASN" >> ip_country.csv
done

# Remove first 2 line of data at the top of the file
sed -i '1,2d' ip_country.csv

# Insert IP, Country and ASN field at the top of the file
sed -i '1i\IP,Country,ASN' ip_country.csv

echo
echo 'Processed data has been as been saved with filename: ip_country.csv'
