#!/bin/bash
# url: http://pank.org/scripts/
# description: add X-Country to mail header
# comment: bash
# platform: freebsd, linux
#
# IP to Country mapping database: http://ip-to-country.webhosting.info/downloads/ip-to-country.csv.zip
# Country code: http://www.iana.org/cctld/cctld-whois.htm
# Needs procmail, formail /usr/ports/mail/procmail

XCOUNTRY_PATH=/usr/local/xcountry
TEMP=/tmp/xcountry$$

iptocountry() {
    if [ -z $1 ] ; then
        echo N/A
        return
    fi
    cd $XCOUNTRY_PATH
    IP=$1
    IFS=.
    set $IP
    IP=$[$1*16777216+$2*65536+$3*256+$4]
    C=`{ echo \"$IP\"
         cat $1.txt 
       } | sort | grep -B1 $IP | head -1 | tr -d \" | cut -d, -f3`
    if [ ${#C} -gt 3 ] ; then
        echo N/A
    else
        echo $C
    fi
}

isprivateip() {
    echo $1 | egrep -q "(192\.168|172\.(1[6-9]|2[0-9]|3[01])|10)\."
}

if [ -z $1 ] ; then
    cat > $TEMP
else
    if [ -f $1 ] ; then
        cp $1 $TEMP
    else
        if [ $1 = "-h" ] ; then
            echo "Usage: `basename $0` {IP|file}"
            exit
        else
            if echo $1 | egrep -q '^([0-9]{1,3}\.){3}[0-9]{1,3}$' ; then
                if isprivateip $1 ; then
                    echo N/A
                else
                    iptocountry $1
                fi
                exit
            else
                echo Invalid IP
                exit 1
            fi
        fi
    fi
fi

IP=`cat $TEMP | formail -x Received | awk -F"[][]" '/\[[0-9]+\./ {print $2}' | grep -v 127.0.0.1 | tail -1`
if [ -z $IP ] ; then
    COUNTRY=Local
else
    if isprivateip $IP ; then
        IP1=$IP
        IP=`cat $TEMP | formail -x Received | awk -F"[][]" '/\[[0-9]+\./ {print $2}' | grep -v 127.0.0.1 | tail -2 | head -1`
        if [ $IP = $IP1 ] ; then
            COUNTRY=Local
        else
            COUNTRY=`iptocountry $IP`
        fi
    else
        COUNTRY=`iptocountry $IP`    
    fi
fi

cat $TEMP | formail -A "X-Country: $COUNTRY"
rm $TEMP