#!/bin/sh
#	program:	localad
#	release:	1.5.0
#	input:		optional nameserver to direct queries to.
#	output:		IP address of the localhost on stdout,
#			or the word "ERROR" (distinguishable from a real
#			record because it has no periods in it).
#	exit value:	0 if succeeds, 1 if fails (and "ERROR" output).
#
# Copyright (C) 1993-2000 Paul A. Balyoz <pab@domtools.com>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#

TMP=/tmp/`basename $0`.$$

usage() {
        echo "usage: $0 [@nameserver]" >&2
        echo 'ERROR'
        exit 1
}

if test $# -gt 1; then
        usage
fi

atnameserver=
if test $# -gt 0; then
	case "$1" in
		@*)  atnameserver="$1" ;;
		*)   usage ;;
	esac
fi

# Attempt 1: if hostname has domain in it, do a PTR query on it (BSD).

h="`hostname 2> /dev/null`"
if test $? -eq 0; then
	if test `echo "$h" | awk -F. '{print NF}'` -gt 1; then
		case "$h" in		# tack on ending period if needed
			*.)	;;
			*)	h="${h}." ;;
		esac
		d="`/usr/local/domtools/bin/address $atnameserver $h`"
		if test $? -eq 0; then
			echo "$d"
			exit 0
		fi
	fi
fi

# Attempt 2: run netstat and parse lines to locate IP address.
# (since this parses output of netstat, it may be very system dependent)

rm -f $TMP
netstat -in | tail +2 | while l="`line`"; do
	if test `echo "$l" | awk '{print $1}'` != "lo0"; then
		b=`echo "$l" | awk '{print $3}'`
		a=`echo "$l" | awk '{print $4}'`
		if test x"$a" = x"127.0.0.1"; then
			a=""
		else
			case "$b" in
			   "<Link>"*) a="" ;;
				   *) if test "`/usr/local/domtools/bin/type $a 2>/dev/null`" = "forward"; then
					# can't simply echo & exit here, because while loop is a subshell!
					echo $a > $TMP
					break
				fi ;;
			esac
		fi
	fi
done
if test -f $TMP; then
	a=`cat $TMP`
	rm -f $TMP
	if test x"$a" != x""; then
		echo "$a"
		exit 0
	fi
fi

# All attempts failed.  More suggestions are welcome!

echo "localad: cannot determine the IP address of this host." >&2
echo 'ERROR'
exit 1
