#!BOURNESHELL
#	program:	localad
#	input:		none.
#	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).

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


# 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="`DOMBIN/address $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 "`DOMBIN/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
