#!/bin/bash


DIG="/cygdrive/c/PROGRAMS/BIND/bin/dig"


for i in test tr rm cut grep awk cat cygsort uniq; do

	if  ! testpath=`which "$i" 2>/dev/null`; then
		echo "Required command $1 not found" >/dev/stderr
		exit 1
	fi

	if ! test -x "$testpath"; then
		echo "Required command $1 not executable" > /dev/stderr
		exit 1
	fi
done

if ! test -x $DIG; then
	echo "DIG $DIG is not executable!" > /dev/stderr
fi

function usage()
{
        echo "usage: $0 -t translation_file -p translation_ip [-d dnsserver] [-n]"
	echo "   -t translation_file : file containing output of \"show ip nat translations\""
	echo "   -p translation_ip   : IP Address entries are translated too."
	echo "   -d dnsserver        : which server to lookup reverse names"
	echo "   -n                  : turn off dns lookups"
        exit 1
}

function cleanup_trap()
{
        cleanup 1
}


function cleanup()
{
        if [[ "$TMPFILE" != "" ]]; then rm -f $TMPFILE; fi
        if [[ "$TMPFILE1" != "" ]]; then rm -f $TMPFILE1; fi
        exit $1
}

trap cleanup_trap SIGKILL SIGHUP SIGTRAP SIGINT SIGABRT SIGUSR1 SIGURG SIGTERM SIGILL  SIGQUIT SIGUSR2 SIGWINCH SIGSEGV


if [[ "$#" < "3" ]]; then usage; fi

PROGNAME=`basename $0`
TMPFILE=`mktemp -q /tmp/$PROGNAME.XXXXXXXXX`
if [ $? -ne 0 ]; then
        echo "$0: Can't create temp file, exiting..."
        cleanup 1
fi
TMPFILE1=`mktemp -q /tmp/$PROGNAME.XXXXXXXXX`
if [ $? -ne 0 ]; then
        echo "$0: Can't create temp file, exiting..."
        cleanup 1
fi

DNS=''
NODNS=''
while getopts "t:d:p:n?h" opt; do
        case "$opt" in
	t) translations=`echo \'$OPTARG\' |  tr -c -d "[[:alnum:]@.\-\_]"`;;
	d) DNS=`echo \'$OPTARG\' |  tr -c -d "[[:alnum:]@.\-\_]"`;;
	p) translation_ip=`echo \'$OPTARG\' |  tr -c -d "[[:alnum:]@.\-\_]"`;;
	n) NODNS="yes";;
        *) usage;;
        esac;
done

if [[ "$translations" == "" ]]; then
	usage
fi

if [[ "$translation_ip" == "" ]]; then
	usage
fi


if [[ "$DNS" != "" ]]; then
	DNS="@$DNS"
fi



grep $translation_ip $translations | awk '{ print $3}' | cut -f1 -d':' | cygsort | uniq | tr -c -d "[[:alnum:]@.\-\_\n]" > $TMPFILE

while read i ; do 
	COUNT=`grep -c $i $translations`
	if [[ "$NODNS" != "yes" ]] ; then
		NAME=`$DIG +short -x  $i $DNS | tr "\n\r" " "` 
	fi
	echo "$COUNT $i $NAME" 
done > $TMPFILE1 < "$TMPFILE"

cat $TMPFILE1 | cygsort -k1 -rn

cleanup 0

