#!/bin/sh
#	program:	localdom
#	release:	1.5.0
#	input:		optional nameserver to direct queries to.
#	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).
#
# 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.
#

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: 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="`/usr/local/domtools/bin/localad $atnameserver`"
if test $? -eq 0; then
	inv="`/usr/local/domtools/bin/f2iaddr $a`"
	if test $? -eq 0; then
		d="`/usr/local/domtools/bin/ptr $atnameserver $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
