#!BOURNESHELL
#	program:	localdom
#	input:		none.
#	output:		domain name of the localhost on stdout,
#			or the word "ERROR" (distinguishable from a real
#			record because it has no period on the end).
#	exit value:	0 if succeeds, 1 if fails (and "ERROR" output).


# Attempt 1: hostname may have domain in it (BSD).

h="`hostname 2> /dev/null`"
if test $? -eq 0; then
	if test `echo "$h" | awk -F. '{print NF}'` -gt 1; then
		# now remove hostname part:
		d=`echo "$h" | awk -F. '{for (i=2; i<NF; i++) {printf "%s.", $i} print $NF}'`
		case "$d" in		# tack on ending period if needed
			*.)	;;
			*)	d="${d}." ;;
		esac
		echo "$d"
		exit 0
	fi
fi

# Attempt 2: "domain" line in resolv.conf.

res=""
test -f /etc/resolv.conf && res="/etc/resolv.conf"
test -f /usr/etc/resolv.conf && res="/usr/etc/resolv.conf"
if test x"$res" != x""; then
	d="`grep '^domain ' $res 2>/dev/null`"
	if test $? -eq 0; then
		if test `echo $d | awk '{print NF}'` -ge 2; then
			d="`echo $d | awk '{print $2}'`"
			case "$d" in
				*.)	;;
				*)	d="${d}." ;;
			esac
			echo "$d"
			exit 0
		fi
	fi
fi

# Attempt 3: PTR query from localhost's IP address

a="`DOMBIN/localad`"
if test $? -eq 0; then
	inv="`DOMBIN/f2iaddr $a`"
	if test $? -eq 0; then
		d="`DOMBIN/ptr $inv`"
		if test $? -eq 0; then
			# now remove hostname part:
			d=`echo "$d" | awk -F. '{for (i=2; i<NF; i++) {printf "%s.", $i} print $NF}'`
			case "$d" in		# tack on ending period if needed
				*.)	;;
				*)	d="${d}." ;;
			esac
			echo "$d"
			exit 0
		fi
	fi
fi

# All attempts failed.  More suggestions are welcome!

echo "localdom: cannot determine which domain this host belongs to." >&2
echo 'ERROR'
exit 1
