#!/bin/sh
# $Id: reverse_dns.sh 11 2015-02-21 09:42:46Z jo $
#
# Usage: reverse_dns.sh IP
# Uses the dnsmasq query log to lookup the name 
# that was last queried to return the given IP.
#
# This has been tested on debian and asuswrt. Plese
# report successful tests on other platforms.
#
# Author: Joachim Zobel <jz-2014@heute-morgen.de>
# License: Consider this MIT style licensed. You can 
#   do as you ike, but you must not remove my name.
#

IP=$1
qmIP=`echo $IP | sed 's#\.#\\.#g' `
LOG=/var/log/dnsmasq.log

IP_regex='^[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}$'
# Skip if it is not an IP
if ! echo $IP | grep -q $IP_regex; then
  echo -n $IP
  exit 
fi

IP_private='\(^127\.\)\|\(^192\.168\.\)\|\(^10\.\)\|\(^172\.1[6-9]\.\)\|\(^172\.2[0-9]\.\)\|\(^172\.3[0-1]\.\)'
HOST=nslookup
if type host > /dev/null 2>&1; then
  # echo "No need for nslookup, host is there"
  HOST=host
fi
# Do a dns lookup, if it is a local IP
if echo $IP | grep -q $IP_private; then
  RTN=`$HOST $IP | \
        sed 's#\s\+#\n#g' | \
        grep -v '^$' | \
        tail -1 | tr -d '\n' | \
        sed 's#.$##' `
  if echo $RTN | grep -q NXDOMAIN; then
    echo -n $IP
  else
    echo -n "$RTN"
  fi 
  exit
fi

# This is a very bad replacement
# since it reads the whole file 
# into a buffer.
# This may work, but is dog slow.
TAC='sed 1!G;h;$!d'
if type tac > /dev/null 2>&1; then
  # echo "No need for sed, tac is there"
  TAC=tac
fi

NAME=`$TAC $LOG | \
  grep " is $IP" | head -1 | \
  sed "s#.* \([^ ]*\) is $qmIP.*#\1#" `

if [ -z "$NAME" ]; then
  echo -n $IP
else
  echo -n $NAME
fi

