#! /bin/sh
#
# xcathostname - lookup hostname for each IP.
#		 Print to STDOUT name with most dots.
#		 Maybe assigned to 'RESOLVE_HOSTNAME_COMMAND='
#
# Copyright (C) 2010 Andrew V. Stepanov <stanv@altlinux.org>
#

ip_list() {
	/sbin/ip addr list scope global |
	sed -n 's|^[[:space:]]*inet[[:space:]]\+\([0-9]\+\.[0-9]\+\.[0-9]\+\.[0-9]\+\)/.*|\1|p'
}

NAME=
STR=
LEN1=
LEN2=

if ! which 'resolve' >/dev/null 2>&1; then
	hostname
	exit 0
fi

for ip in $(ip_list); do
	STR="$(resolve -t 2 "$ip" 2>/dev/null)" || continue
	# Parse `resolve' answer
	STR="${STR#*:}"
	STR="${STR//,/}"

	# Take first name
	if [ -z "$NAME" ]; then
		NAME="${STR%% *}"
	fi

	# Lookup for hostname with more dots `.'
	for n in $STR; do
		LEN1="${n//[^.]/}"
		LEN2="${NAME//[^.]/}"
		LEN1="${#LEN1}"
		LEN2="${#LEN2}"
		if [ $LEN1 -gt $LEN2 ]; then
			NAME="$n"
		fi
	done
done

if [ -z "$NAME" ]; then
	NAME="$(hostname)"
fi

echo "$NAME"
exit 0
