#!/bin/ksh

#pragma ident       "@(#)lookuphost 1.6     01/05/23 SMI"

#
#       Copyright (C) 1997 Sun Microsystems, Inc.
#


# Usage: lookuphost hostname
#
# First it looks in /etc/hosts. If not found, calls host2ipaddr.c to 
# lookup the hostname in the name service(s), via /etc/nsswitch.conf 
# machinery. If ultimately found, prints its ip address on stdout,
# and exits 0. If not found, just prints nothing on stdout and 
# exits 0.
#
# Special case: it's legal for the hostname argument to already be
# an ip address in the a.b.c.d notation, in which case this script
# will echo it on stdout and exit 0.
#
# If duplicate entries for the host exist in the /etc/hosts file, then
# the first one is chosen and a warning issued on the system console
# logs. In addition, the exit code for the script in this case is 2,
# so that calling programs can distinguish between the occurrence of
# one or more entries in the /etc/hosts file.
#
# The motivation for having this shell script is to reduce our 
# dependencies # on having a name service that responds quickly.   
# The emphasis here is on # the word quickly. One might imagine that 
# the /etc/nsswitch.conf file takes care of this already, by 
# having its search list of the form:
#       hosts:  nisplus dns [NOTFOUND=return] files
# However, the nsswitch machinery has a very long timeout before it 
# will give up on nisplus and go on to look in the files.  It takes 
# as much as four minutes.

log_trace lookuphost
pre="SUNWcluster.lookuphost"
tmpdir=/var/opt/SUNWcluster/run
tmpfile=${tmpdir}/egrep.host.$$
hostname=$1
egrep '^[^#]*[	 ]'${hostname}'[	 ]|^[^#]*[	 ]'${hostname}'$' \
 < /etc/hosts > ${tmpfile} 2> /dev/null
if [[ $? -eq 0 && -s ${tmpfile} ]]; then
  let lines="`wc -l < ${tmpfile}`"
  if (( lines == 1 )); then
    awk '{print $1}' < ${tmpfile}
  elif (( lines > 1 )); then
    # More than one occurrence in /etc/hosts.  
    # Use first entry, and warn the administrator
    answer=$(awk '{print $1; exit}' < ${tmpfile})
    log_info "${pre}.3010" "/etc/hosts has multiple entries for ${hostname}"
    print ${answer}
    /bin/rm -f ${tmpfile}
    exit 2
  fi
else
  # Did not find the hostname in /etc/hosts.  
  answer=$(host2ipaddr $hostname)
  ret=$?
  if [[ ${ret} -eq 0 || ${ret} -eq 2 ]]; then
    print ${answer}
  fi
fi

/bin/rm -f ${tmpfile}
log_trace_end lookuphost
exit 0
