#!/bin/sh
#
# bbgetipaddr.sh
#
# BIG BROTHER script to retrieve IP address from bb-hosts file
# Robert-Andre Croteau
# Version 1.9
# Mar 13th, 2002
#
# (c) Copyright Quest Software, Inc.  1997-2002  All rights reserved.
#
# Get the associated IP address with the host name
#
# Usage: bbgetipaddr.sh <hostname>
#
# argument: hostname must be in the form xxx.yyy.zzz
#


if [ "$#" -ne 1 ]
then
	exit 1
fi

if test ! "$BBTMP"                      # GET DEFINITIONS IF NEEDED
then
        . $BBHOME/etc/bbdef.sh          # INCLUDE STANDARD DEFINITIONS
fi

HOSTNAME="$1"
   
# Are we using Fully Qualified Domain Naming (FQDN) ? 
if [ "$FQDN" = TRUE ]
then
	# Try with bb-hosts lines comprised of only IP address and host name
	FQDNLINE=`$GREP "[ 	]${HOSTNAME}$" $BBHOSTS | $GREP "^[0-9]" 2>/dev/null`
	if [ "$?" -ne 0 ]
	then
		# Try with bb-hosts lines comprised of of more than only IP address and host name
		FQDNLINE=`$GREP "[ 	]${HOSTNAME}[ 	]" $BBHOSTS | $GREP "^[0-9]" 2>/dev/null`
	fi
else
	OLDIFS=$IFS
	IFS='.'
	set $HOSTNAME
	IFS=$OLDIFS
	HOSTNAME=$1
	# Try with bb-hosts lines comprised of only IP address and host name
	FQDNLINE=`$GREP "[ 	]${HOSTNAME}$" $BBHOSTS | $GREP -v "^[0-9]" 2>/dev/null`
	if [ "$?" -ne 0 ]
	then
		# Try with bb-hosts lines comprised of of more than only IP address and host name
		FQDNLINE=`$GREP "[ 	]${HOSTNAME}[\. 	]" $BBHOSTS | $GREP -v "^[0-9]" 2>/dev/null`
	fi
fi

# Do we have a match ?
if [ "$FQDNLINE" != "" ]
then
	# Yes, then retrieve IP address
	# Hummm, what happens if FQDNLINE is more than a single entry in bb-hosts ? can it ?
	OLDIFS=$IFS
	IFS=' '
	set $FQDNLINE >/dev/null 2>&1
	IFS=$OLDIFS
	# If set was successful and at least 2 args we defined (which should always be the case)
	if [ "$?" -eq 0 -a "$#" -gt 1 ]
	then
		echo "$1"
		exit 0
	fi
fi

# Made it this far, then no good
exit 1
