#!/bin/ksh
#
# ident	"@(#)sc_update_hosts.ksh	1.3	05/01/19 SMI"
#
# Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.

#
# sc_update_hosts.ksh
#

# Program name and args list
typeset -r PROG=${0##*/}
typeset -r ARGS=$*

typeset -x TEXTDOMAIN=SUNW_SC_CMD
typeset -x TEXTDOMAINDIR=/usr/cluster/lib/locale
typeset    SC_BASEDIR=${SC_BASEDIR:-}
typeset -r SC_CONFIG=${SC_CONFIG:-${SC_BASEDIR}/etc/cluster/ccr/infrastructure}
typeset HOSTS=${SC_BASEDIR}/etc/inet/hosts
typeset SC_IP=${SC_BASEDIR}/usr/cluster/lib/scadmin/lib/sc_ip.pl

#####################################################
#
# sc_addnodes_in_hosts
#
#      	Updates the local host file with the IP addresses and
#	hostnames of all nodes in the cluster .
#
#       Return:
#               zero            Success
#               non-zero        Failure
#
#####################################################

sc_addnodes_in_hosts()
{
	typeset cluster_nodes="$(sed -n 's/^cluster\.nodes\.[1-9][0-9]*\.name[ 	]\(.*\)/\1/p' ${SC_CONFIG})"

	if [[ -z "${cluster_nodes}" ]];then
		return 1
	fi
	# Iterate over all the nodes in the cluster
	for node in $cluster_nodes
	do
		node_ip=$(${SC_IP} get_ip_in_hosts ${node})
		if [[ -n ${node_ip} ]];then
			continue
		fi
		node_ip=$(${SC_IP} convert_to_ip ${node})
		if [[ -z ${node_ip} ]];then
			printf "%s:  $(gettext 'Can not resolve IP address for %s')\n" ${PROG} ${node} >&2
			continue
		fi
		node_again=$(${SC_IP} get_name_in_hosts ${node_ip})
		if [[ -n ${node_again} ]];then
			printf "%s:  $(gettext 'IP address conflict for node %s : %s')\n" "${PROG}" "${node}" "${node_ip}" >&2
			printf "%s:  $(gettext 'Failed to add node %s in %s')\n" "${PROG}" "${node}" "${HOSTS}" >&2
			continue
		fi
		# Write the IP address and the hostname
		echo "${node_ip}	${node} # Cluster Node" >> ${HOSTS}
		if [[ $? -ne 0 ]];then
			printf "%s:  $(gettext 'Failed to add node %s in %s')\n" "${PROG}" "${node}" "${HOSTS}" >&2
		fi
	done
	return 0
}

sc_addnodes_in_hosts || exit 1

exit 0
