#!/bin/sh

# Copyright  2003 Sun Microsystems, Inc. All rights reserved. 

# U.S. Government Rights - Commercial software. Government users 
# are subject to the Sun Microsystems, Inc. standard license agreement 
# and applicable provisions of the FAR and its supplements.

# Use is subject to license terms. 

# This distribution may include materials developed by third parties.
# Sun, Sun Microsystems, the Sun logo, Java and Sun Java[TM] System are 
# trademarks or registered trademarks of Sun Microsystems, Inc. in 
# the U.S. and other countries. 



# Copyright  2003 Sun Microsystems, Inc. Tous droits rservs.

# L'utilisation est soumise aux termes du contrat de licence.

# Cette distribution peut comprendre des composants dvelopps par 
# des tierces parties.

# Sun, Sun Microsystems, le logo Sun, Java et Sun Java[TM] System sont des marques 
# de fabrique ou des marques dposes de Sun Microsystems, Inc. aux 
# Etats-Unis et dans d'autres pays.


#All defines are listed here..
#General utils
platform="`uname`"
if [ ${platform} = "Linux" ]
then
ID=/usr/bin/id
ECHO=/bin/echo
DATE=/bin/date
SED=/bin/sed
AWK=/bin/awk
RM=/bin/rm
DIRNAME=/usr/bin/dirname
CUT=/bin/cut
GETTEXT=/bin/gettext
else
ID=/usr/bin/id
ECHO=/usr/bin/echo
DATE=/usr/bin/date
SED=/usr/bin/sed
AWK=/usr/bin/awk
RM=/usr/bin/rm
DIRNAME=/usr/bin/dirname
CUT=/usr/bin/cut
GETTEXT=/usr/bin/gettext
fi


#Script Specific defines

. %CONFIG_HOME%/asenv.conf
JAVA_HOME=${AS_JAVA}
export JAVA_HOME

#i18n stuff
TEXTDOMAIN=clsetup
TEXTDOMAINDIR=${AS_INSTALL}/lib/messages
export TEXTDOMAIN
export TEXTDOMAINDIR

# Error Codes
CLSETUP_SUCCESS=0
CLSETUP_USAGE_ERROR=2

CLSETUP_INSTANCEFILE_NOTFOUND=3
CLSETUP_CANNOTREAD_INSTANCEFILE=4

CLSETUP_RESOURCEFILE_NOTFOUND=5
CLSETUP_CANNOTREAD_RESOURCEFILE=6

CLSETUP_PASSWORDFILE_NOTFOUND=7
CLSETUP_CANNOTREAD_PASSWORDFILE=8

CLSETUP_INVALID_USER=9
CLSETUP_ASADMIN_NOTFOUND=10
CLSETUP_HADBM_NOTFOUND=11

CLSETUP_ERROR_CREATE_TMPFILE=12
CLSETUP_SESSIONSTORE_FAILED=13
CLSETUP_HADBDB_FAILED=14
CLSETUP_HADBGETURL_FAILED=15
CLSETUP_USER_EXIT=16

CLSETUP_CLUSTER_VERIFICATION_FAILED=17
CLSETUP_CLUSTER_VERIFICATION_SERVER_DTD_NOT_FOUND=18

#Logfile location where the output is logged.
LOGFILE=/var/tmp/clsetup.log


#Configuration file that holds information about instances that are 
#part of one cluster. Can be overridden by passing --instancefile
#to this script.'

INSTANCEFILE=${AS_CONFIG}/clinstance.conf

#Configuration file that holds information about cluster objects.
#Can be overridden by passing --resourcefile to this script.'

RESOURCEFILE=${AS_CONFIG}/clresource.conf


#Password file that holds admin server password.
#Can be overridden by passing --passwordfile to this script.'

PASSWORDFILE=${AS_CONFIG}/clpassword.conf

#New option to run verification instead of configuration
VERIFY_CLUSTER="false"


# awk script used by this script to parse the various information files.
AWKFILE=${AS_INSTALL}/bin/common.awk

# Notations for asadmin and hadbm commands.
HADBM=${AS_HADB}/bin/hadbm
ASADMIN=${AS_INSTALL}/bin/asadmin


#Show welcome text and get confirmation from the user before proceding.
ShowWelcome()
{
${ECHO} "`${GETTEXT} 'Welcome to Sun Java System Application Server Enterprise Edition 7 2004Q2'`"
${ECHO} "`${GETTEXT} 'Cluster Setup Program.'`"
${ECHO} "===================================================================="
${ECHO} "`${GETTEXT} 'Please look carefully at the assumptions made by this program prior'`"
${ECHO} "`${GETTEXT} 'to starting the configuration process.'`"
${ECHO} " "
${ECHO} "`${GETTEXT} '1). Make sure your machine is configured properly to run RSH/SSH commands.'`"
${ECHO} " "
${ECHO} "`${GETTEXT} '2). No inetd configuration will be done by this script.'`"
${ECHO} " "
${ECHO} "`${GETTEXT} '3). Shared Memory settings requires for HADB Commands will not be set'`"
${ECHO} "`${GETTEXT} 'by this script.It is assumed that they have been preset to desired values.'`"
${ECHO} " "
${ECHO} "`${GETTEXT} '4). LoadBalancer configuration will not be handled by this program.'`"
${ECHO} " "
${ECHO} "`${GETTEXT} '5). Make sure that the admin server is up and running on this machine.'`"
${ECHO} "===================================================================="
${ECHO} " "
${ECHO} "`${GETTEXT} 'Do you want to start configuring your cluster? [Yes/No]'` "
read prompt

reponse=`${ECHO} "$prompt" | tr "[a-z]" "[A-Z]"`
if [ "$reponse" = "`${GETTEXT} 'YES'`" ] 
then
	return
fi
${ECHO}
${ECHO} "`${GETTEXT} 'Exiting upon your choice...'`"
${ECHO}
${ECHO} " " >> ${LOGFILE}
${ECHO} "#######################################################################" >> ${LOGFILE}
${ECHO} "`${GETTEXT} 'Cluster Setup Script. Execution end time'` `${DATE} +%D` `${DATE} +%H:%M:%S`" >> ${LOGFILE}
${ECHO} "#######################################################################" >> ${LOGFILE}
exit ${CLSETUP_USER_EXIT}
}


CheckUsage()
{
if [ "${1}" = "--help" ]
then
	ShowUsage
	exit ${CLSETUP_USAGE_ERROR}
fi


# Check if correct number of arguments are passed, otherwise display usage and
# bail out

if [ $# -eq 1 -o $# -eq 3 -o $# -eq 5 -o $# -eq 0 -o $# -eq 2 -o $# -eq 4 -o $# -eq 6 ]
then
	PWDFILE=
	RESFILE=
	INSTFILE=
	ctr=0
	for i in $*
	do
		if [ "${i}" = "--verify" ]
		then
			VERIFY_CLUSTER="true"
		else
		if [ "${i}" = "--instancefile" ]
		then
			INSTFILE="$2"
		else
		if [ "${i}" = "--resourcefile" ]
		then
			RESFILE="$2"
		else
		if [ "${i}" = "--passwordfile" ]
		then
			PWDFILE="$2"
		else
			if [ `expr $ctr % 2` -eq 0 ]
			then
		ShowUsage
	exit ${CLSETUP_USAGE_ERROR}
			fi
		fi
		fi
		fi
		fi
	shift
	ctr=`expr $ctr + 1`
	done	
#If --instancefile argument is passed then this will be set to non empty value
#if so then check if the file exists and readable
   if [ ! -z "${INSTFILE}" ]
   then
	INSTANCEFILE=${INSTFILE}
   fi


#If --resourcefile argument is passed then this will be set to non empty value
#if so then check if the file exists and readable
   if [ ! -z "${RESFILE}" ]
   then
	RESOURCEFILE=${RESFILE}
   fi


#If --passwordfile argument is passed then this will be set to non empty value
#if so then check if the file exists and readable
   if [ ! -z "${PWDFILE}" ]
   then
	PASSWORDFILE=${PWDFILE}
   fi


        if [ ! -f "${INSTANCEFILE}" ]
	then
	   	${ECHO} "${INSTANCEFILE} : `${GETTEXT} 'Instance file does not exist. Please rerun with a valid filename.'`" 
		ShowUsage
       	        exit ${CLSETUP_INSTANCEFILE_NOTFOUND}
	fi
	if [ ! -r "${INSTANCEFILE}" ]
	then
	   	${ECHO} "`${INSTANCEFILE} : ${GETTEXT} 'Instance file is not readable. Please rerun with a valid filename.'`" 
		ShowUsage
       	        exit ${CLSETUP_CANNOTREAD_INSTANCEFILE}
	fi
	
  
	if [ "${VERIFY_CLUSTER}" = "false" ]
	then
		if [ ! -f "${RESOURCEFILE}" ]
		then
	   		${ECHO} "${RESOURCEFILE} : `${GETTEXT} 'Resource file does not exist. Please rerun with a valid filename.'`" 
			ShowUsage
        		exit ${CLSETUP_RESOURCEFILE_NOTFOUND}
   		fi
		if [ ! -r "${RESOURCEFILE}" ]
		then
		   	${ECHO} "${RESOURCEFILE} : `${GETTEXT} 'Resource file is not readable. Please rerun with a valid filename.'`" 
			ShowUsage
       		        exit ${CLSETUP_CANNOTREAD_RESOURCEFILE}
			
		fi
	fi
	


	if [ ! -f "${PASSWORDFILE}" ]
	then
	   	${ECHO} "${PASSWORDFILE} : `${GETTEXT} 'Password file does not exist. Please rerun with a valid filename.'`" 
		ShowUsage
        	exit ${CLSETUP_PASSWORDFILE_NOTFOUND}
   	fi
	if [ ! -r "${PASSWORDFILE}" ]
	then
	   	${ECHO} "${PASSWORDFILE} : `${GETTEXT} 'Password file is not readable. Please rerun with a valid filename.'`" 
		ShowUsage
       	        exit ${CLSETUP_CANNOTREAD_PASSWORDFILE}
		
	fi

#If the number of arguments is not correct then display usage error and bail out
else
		ShowUsage
		exit ${CLSETUP_USAGE_ERROR}
fi	
}

#Check if the user running this script is root user. If not bail out
CheckUser()
{
if [ `${ID} | ${AWK} '{print $1}'` != "uid=0(root)" ]
then
	${ECHO} "`${GETTEXT} 'This program can only be run by a root user.'`"
	exit ${CLSETUP_INVALID_USER}
fi
}


#This method checks if asadmin is available in the same directory where
#this script resides. If not this will bail out..
CheckAsadmin()
{
if [ ! -f ${ASADMIN} ]
then
	writeToLog "`${GETTEXT} 'Could not locate asadmin command on this machine. Exiting...'`"
	exit ${CLSETUP_ASADMIN_NOT_FOUND}
else
	WriteToLog "\t `${GETTEXT} 'Using'` ${ASADMIN}"
fi
}

#This method checks if hadbm is available in the specified directory.
#This script is a one time configuration script that should be
#run on a machine where application server and hadb are pre installed
#If this script cannot find hadbm then it will bail out
CheckHadbm()
{
if [ ! -f ${HADBM} ]
then
	WriteToLog "`${GETTEXT} 'Could not locate hadbm command on this machine. Exiting...'`"
	exit ${CLSETUP_HADBM_NOT_FOUND}
else
	WriteToLog "\t `${GETTEXT} 'Using'` ${HADBM}"
fi
}

#This method is used to read the [INSTANCES] section of ${INSTANCESFILE}
#and use the values to create the instances. These values are used
#repeatedly throughout the scripts to configure the cluster.
#First it creates a temporary file /var/tmp/clsetupinstance to record
#instances information in single line format. This file will then be
#read and the cluster configuration commands are repeated for every
#instance. The admin password required to connect to the admin server
#will be taken from ${PASSWORDFILE}.
CreateInstances()
{
#Read the instance information file and use password file to create instances
${AWK} -f ${AWKFILE} SECTIONNAME="[INSTANCES]" ${INSTANCEFILE} > /var/tmp/clsetupinstance
WriteToLog " "
WriteToLog " "
WriteToLog "\t `${GETTEXT} 'CREATING AND CONFIGURING APPLICATION SERVER INSTANCES...'`"
#Check if the file is created if not bail out could be that /var/tmp is write 
#protected. 
if [ ! -f /var/tmp/clsetupinstance ]
then
	WriteToLog "`${GETTEXT} 'This configuration script creates a temporary file'`"
	WriteToLog "`${GETTEXT} 'under /var/tmp. Please make sure that your /var/tmp directory'`"
	WriteToLog "`${GETTEXT} 'is available and is writable. Please re run this script'`"
	WriteToLog "`${GETTEXT} 'after verifying the same.'`"
	exit ${CLSETUP_ERROR_CREATE_TMPFILE}
fi

while
	read line 
do
	instancename=`${ECHO} $line | ${CUT} -f1 -d ":"`
	adminuser=`${ECHO} $line | ${CUT} -f2 -d ":"`
	hostname=`${ECHO} $line | ${CUT} -f3 -d ":"`
	adminport=`${ECHO} $line | ${CUT} -f4 -d ":"`
	domainname=`${ECHO} $line | ${CUT} -f5 -d ":"`
	instanceport=`${ECHO} $line | ${CUT} -f6 -d ":"`


#Create instance first
#Check if the instance to be created exists, if so then skip this step.
	WriteToLog " "
	WriteToLog " "
	WriteToLog "\t\t `${GETTEXT} 'Checking for instance'` ${instancename}"
	CMD="${ASADMIN} show-instance-status --user ${adminuser} --passwordfile ${PASSWORDFILE} --host ${hostname} --port ${adminport} ${instancename}"
	WriteToLog " "
	WriteToLog "\t\t $CMD"
	WriteToLog " "
	$CMD 1>>${LOGFILE} 2>>${LOGFILE}
	if [ ! $? = 0 ]
	then
#Create instance now.
	   WriteToLog " "
	   WriteToLog " "
	   WriteToLog "\t\t `${GETTEXT} 'Creating instance'` ${instancename}"
	   CMD="${ASADMIN} create-instance --user ${adminuser} --passwordfile ${PASSWORDFILE} --host ${hostname} --port ${adminport} --domain ${domainname} --instanceport ${instanceport} ${instancename}"
	   WriteToLog " "
	   WriteToLog "\t\t $CMD"
	   WriteToLog " "
	   $CMD 1>>${LOGFILE} 2>>${LOGFILE}
	   if [ $? = 0 ]
	   then
		WriteToLog "\t\t `${GETTEXT} 'Successfully created Application Server Instance'` ${instancename}."
	   	WriteToLog "\t\t `${GETTEXT} 'Starting the instance. '`"
	   	CMD="${ASADMIN} start-instance --user ${adminuser} --passwordfile ${PASSWORDFILE} --host ${hostname} --port ${adminport} --domain ${domainname} ${instancename}"
	   	WriteToLog " "
	   	WriteToLog "\t\t $CMD"
	   	WriteToLog " "
	   	$CMD 1>>${LOGFILE} 2>>${LOGFILE}
	else
		WriteToLog "\t\t `${GETTEXT} 'ERRORS in Creating Application Server instance'` ${instancename}." 
	   fi
	else
	   WriteToLog " "
	   WriteToLog "\t\t `${GETTEXT} 'Instance already exists. Skipping creation part'`"
	   WriteToLog "\t\t `${GETTEXT} 'Starting the instance. '`"
	   CMD="${ASADMIN} start-instance --user ${adminuser} --passwordfile ${PASSWORDFILE} --host ${hostname} --port ${adminport} --domain ${domainname} ${instancename}"
	   WriteToLog " "
	   WriteToLog "\t\t $CMD"
	   WriteToLog " "
	   $CMD 1>>${LOGFILE} 2>>${LOGFILE}
	fi
	   WriteToLog " "
	   WriteToLog " "
#Create connection pool for the instance currently read
	WriteToLog "\t\t `${GETTEXT} 'Creating JDBC Connection Pool in instance'` ${instancename}"
	CreateJdbcpl ${adminuser} ${hostname} ${adminport} ${instancename}
#Register JDBC Datasource for the instance currently read
	WriteToLog "\t\t `${GETTEXT} 'Registering the datasource in instance'` ${instancename}"
	RegisterJdbcresource ${adminuser} ${hostname} ${adminport} ${instancename}
#Configure Session Persistence for the instance currently read
        persistentType=`${AWK} -f ${AWKFILE} SECTIONNAME="[SESSION_PERSISTENCE]" GETTYPE="type" ${RESOURCEFILE}`
	persistentTypeMessage="Configuring persistent type to $persistentType in instance"
	WriteToLog "\t\t `${GETTEXT} "$persistentTypeMessage"` ${instancename}"
	CreateSessionpersistence ${adminuser} ${hostname} ${adminport} ${instancename}
#Configure Ejb Persistence for the instance currently read
	SetSfsbPersistence ${adminuser} ${hostname} ${adminport} ${instancename}
#Configure cluster-id property for the instance currently read
	SetClusterId ${adminuser} ${hostname} ${adminport} ${instancename}
#Reconfigure instances to update the newly added information.
	WriteToLog "\t\t `${GETTEXT} 'Reconfiguring instance'` ${instancename}"
	CMD="${ASADMIN} reconfig -u ${adminuser} --passwordfile ${PASSWORDFILE}  --host ${hostname} --port ${adminport} ${instancename}"
	WriteToLog " "
	WriteToLog "\t\t $CMD"
	WriteToLog " "
	$CMD 1>>${LOGFILE} 2>>${LOGFILE}
	if [ $? = 0 ]
	then
		WriteToLog "\t\t `${GETTEXT} 'Successfully reconfigured instance'` ${instancename}."
	else
		WriteToLog "\t\t `${GETTEXT} 'Could not reconfigure instance'` ${instancename}."
		WriteToLog "\t\t `${GETTEXT} 'Please set it through asadmin command : '` $CMD"
	fi
done < /var/tmp/clsetupinstance
${RM} -f /var/tmp/clsetupinstance
}

#This method creates session store in the newly created HADB Database.
CreateSessionstore()
{
CMD="${ASADMIN} create-session-store `${AWK} -f ${AWKFILE} SECTIONNAME="[SESSION_STORE]" ${RESOURCEFILE} | ${SED} "s/REPLACEURL/${SESSIONSTOREURL}/g"`"
WriteToLog " "
WriteToLog " "
WriteToLog "\t `${GETTEXT} 'CREATING DATABASE TABLES REQUIRED FOR SESSION SETUP...'`"
WriteToLog " "
WriteToLog "\t $CMD \n\n"
$CMD 1>>${LOGFILE} 2>>${LOGFILE}
if [ $? = 0 ]
then
	WriteToLog	"\t `${GETTEXT} 'Session Store created successfully.'`"
else
	WriteToLog	"\t `${GETTEXT} 'Session Store Creation Failed.'`"
	EndProgram ${CLSETUP_SESSIONSTORE_FAILED}
fi
}

#This method Creates JDBC Connection Pool for each instance in the cluster.
#This gets called from CreateInstances and the instance information are passed
#as arguments to this script.
CreateJdbcpl()
{
CMD="${ASADMIN} create-jdbc-connection-pool --user ${1} --passwordfile ${PASSWORDFILE} --host ${2} --port ${3} --instance ${4} --isconnectvalidatereq=true `${AWK} -f ${AWKFILE} SECTIONNAME="[JDBC_CONNECTION_POOL]" ${RESOURCEFILE} | ${SED} "s/REPLACEURL/${CONNECTIONPOOLURL}/g"`"
WriteToLog " "
WriteToLog "\t\t $CMD"
WriteToLog " "
$CMD 1>>${LOGFILE} 2>>${LOGFILE}
if [ $? = 0 ]
then
	WriteToLog	"\t\t `${GETTEXT} 'JDBC Connection Pool created successfully for instance'` ${4}."
else
	WriteToLog	"\t\t `${GETTEXT} 'JDBC Connection Pool creation failed for instance'` ${4}."
fi
WriteToLog " "
WriteToLog " "
WriteToLog " "
}

#This method Registers the datasource for each instance in the cluster.
#This gets called from CreateInstances and the instance information are passed
#as arguments to this script.
RegisterJdbcresource()
{
#Register JDBC Data Source 
CMD="${ASADMIN} create-jdbc-resource --user ${1} --passwordfile ${PASSWORDFILE} --host ${2} --port ${3} --instance ${4} `${AWK} -f ${AWKFILE} SECTIONNAME="[JDBC_RESOURCE]" ${RESOURCEFILE}`"
WriteToLog " "
WriteToLog "\t\t $CMD"
WriteToLog " "
$CMD 1>>${LOGFILE} 2>>${LOGFILE}
if [ $? = 0 ]
then
	WriteToLog	"\t\t `${GETTEXT} 'JDBC Datasource successfully created for instance'` ${4}."
else
	WriteToLog	"\t\t `${GETTEXT} 'Could not create JDBC Datasource creation for instance'` ${4}."
	WriteToLog "\t\t `${GETTEXT} 'Please set it through asadmin command : '` $CMD"
fi
WriteToLog " "
WriteToLog " "
WriteToLog " "
}

#This method Configures the Session Persistence type  for each instance in 
#the cluster.
#This gets called from CreateInstances and the instance information are passed
#as arguments to this script.
CreateSessionpersistence()
{ 
CMD="${ASADMIN} configure-session-persistence --user ${1} --passwordfile ${PASSWORDFILE} --host ${2} --port ${3}  `${AWK} -f ${AWKFILE} SECTIONNAME="[SESSION_PERSISTENCE]" ${RESOURCEFILE}` ${4}"
WriteToLog " "
WriteToLog "\t\t $CMD"
WriteToLog " "
$CMD 1>>${LOGFILE} 2>>${LOGFILE}
if [ $? = 0 ]
then
	WriteToLog	"\t\t `${GETTEXT} 'Persistent type successfully configured for instance'` ${4}."
	CMD="${ASADMIN} set --user ${1} --passwordfile ${PASSWORDFILE} --host ${2} --port ${3}  ${4}.availability-service.availabilityEnabled=true"
	$CMD 1>>${LOGFILE} 2>>${LOGFILE}
	if [ $? = 0 ]
	then
		WriteToLog "\t\t `${GETTEXT} 'Availability enabled to true for instance'` ${4}"
	else
		WriteToLog "\t\t `${GETTEXT} 'Could not enable availability for instance'` ${4}"
		WriteToLog "\t\t `${GETTEXT} 'Please set it through asadmin or cladmin.'`"
		WriteToLog "\t\t `${GETTEXT} 'Please set it through asadmin command : '` $CMD"
	fi
	
	CMD="${ASADMIN} set --user ${1} --passwordfile ${PASSWORDFILE} --host ${2} --port ${3}  ${4}.web-container.availabilityEnabled=true"
	$CMD 1>>${LOGFILE} 2>>${LOGFILE}
	if [ $? = 0 ]
	then
		WriteToLog "\t\t `${GETTEXT} 'web-container availability enabled to true for instance'` ${4}"
	else
		WriteToLog "\t\t `${GETTEXT} 'Could not enable web-container.availabilityEnabled to true for instance'` ${4}"
		WriteToLog "\t\t `${GETTEXT} 'Please set it through asadmin or cladmin.'`"
		WriteToLog "\t\t `${GETTEXT} 'Please set it through asadmin command : '` $CMD"
	fi
else
	WriteToLog	"\t\t `${GETTEXT} 'Could not configure Persistent type for instance'` ${4}."
	WriteToLog "\t\t `${GETTEXT} 'Please set it through asadmin command : '` $CMD"
fi
WriteToLog " "
WriteToLog " "
WriteToLog " "
}

#This method creates a HADB Database with two nodes on local machine.
#The parameter values are read from ${RESOURCEFILE}.
#This method also starts the recently created Database and 
#gives out the JDBC URL info.
CreateHadbdb()
{
CMD="${HADBM} create --installpath=${AS_HADB} --configpath=/etc/opt/SUNWhadb/dbdef `${AWK} -f ${AWKFILE} SECTIONNAME="[HADBINFO]" ${RESOURCEFILE}`"
DBNAME=`echo ${CMD} | ${AWK} '{print $NF}'`
WriteToLog " "
WriteToLog " "
WriteToLog "\t `${GETTEXT} 'CHECKING IF DATABASE EXISTS...'` "
WriteToLog " "
WriteToLog "\t ${HADBM} status ${DBNAME} \n\n"
${HADBM} status ${DBNAME} 1>>${LOGFILE} 2>>${LOGFILE}

if [ $? = 0 ]
then
	WriteToLog "\t `${GETTEXT} 'Database already exists!!. Skipping creation part'`"
else
	WriteToLog " "
	WriteToLog " "
	WriteToLog "\t `${GETTEXT} 'CREATING HADB DATABASE...'` "
	WriteToLog " "
	WriteToLog "\t $CMD \n\n"
	$CMD 1>>${LOGFILE} 2>>${LOGFILE}
	if [ $? = 0 ]
	then
		WriteToLog	"\t `${GETTEXT} 'HADB Database created successfully.'`"
	else
		WriteToLog	"\t `${GETTEXT} 'HADB Database creation failed.'`"
	EndProgram ${CLSETUP_HADBDB_FAILED}
	fi
fi

WriteToLog " "
WriteToLog " "
WriteToLog "\t `${GETTEXT} 'GETTING JDBC URL...'`"
WriteToLog " "
WriteToLog "\t ${HADBM} get jdbcURL ${DBNAME}"
WriteToLog " "
#Find out URL, start the database before getting..
SESSIONSTOREURL=`${HADBM} get jdbcURL --quiet ${DBNAME} | ${CUT} -f2 -d " "`
JDBCURL=`echo ${SESSIONSTOREURL} | ${SED} 's/jdbc:sun:hadb:/ /g' | tr -d " "`
CONNECTIONPOOLURL=`echo ${JDBCURL} | ${SED} 's/:/\\\\\\\:/g'`
if [ $? = 0 ]
then
	WriteToLog	"\t `${GETTEXT} 'URL Retrieved successfully.'`"
else
	WriteToLog	"\t `${GETTEXT} 'Could not retrive URL.'`"
	EndProgram ${CLSETUP_HADBGETURL_FAILED}
fi
}

EndProgram()
{
exitCode=$1
WriteToLog " "
WriteToLog " "
${ECHO} "`${GETTEXT} 'Please refer to the log file'` ${LOGFILE} `${GETTEXT} 'for additional information.'`"
WriteToLog "###################################################################"
WriteToLog "`${GETTEXT} 'Cluster Setup Script. Execution end time'` `${DATE} +%D` `${DATE} +%H:%M:%S`"
WriteToLog "###################################################################"
exit ${exitCode}
}
WriteToLog()
{
Message=$1
${ECHO} $1
${ECHO} $1 >> ${LOGFILE}
}


#This method Configures the SFSB Persistence for an instance.
#This gets called from CreateInstances and the instance information are passed
#as arguments to this script.
SetSfsbPersistence()
{ 
SFSB="`${AWK} -f ${AWKFILE} SECTIONNAME="[EJB_FAILOVER]" GETPROPERTY="sfsb" ${RESOURCEFILE}`"
CMD="${ASADMIN} set --user ${1} --passwordfile ${PASSWORDFILE} --host ${2} --port ${3}  ${4}.ejb-container.availabilityEnabled=${SFSB}"
$CMD 1>>${LOGFILE} 2>>${LOGFILE}
if [ $? = 0 ]
then
	WriteToLog "\t\t `${GETTEXT} 'EJB container availability set to '${SFSB}' for instance'` ${4}"
else
	WriteToLog "\t\t `${GETTEXT} 'Could not set ejb-container.availabilityEnabled attribute for instance'` ${4}"
	WriteToLog "\t\t `${GETTEXT} 'Please set it through asadmin or cladmin.'`"
	WriteToLog "\t\t `${GETTEXT} 'Please set it through asadmin command : '` $CMD"
fi
WriteToLog " "
WriteToLog " "
WriteToLog " "
}

#This method is used to read the [INSTANCES] section of ${INSTANCESFILE}
#and use the values to create the instances. These values are used
#repeatedly throughout the scripts to configure the cluster.
#First it creates a temporary file /var/tmp/clsetupinstance to record
#instances information in single line format. This file will then be
#read and the cluster configuration commands are repeated for every
#instance. The admin password required to connect to the admin server
#will be taken from ${PASSWORDFILE}.
CreateIIOPCluster()
{

RMI_IIOP=`${AWK} -f ${AWKFILE} SECTIONNAME="[RMI_IIOP_FAILOVER]" GETPROPERTY="rmi_iiop" ${RESOURCEFILE}`
if [ "${RMI_IIOP}" = "false" ]
then
	DeleteIIOPCluster
	return
fi

#Read the instance information file and use password file to create instances
${AWK} -f ${AWKFILE} SECTIONNAME="[INSTANCES]" ${INSTANCEFILE} > /var/tmp/clsetupinstance
WriteToLog " "
WriteToLog " "
WriteToLog "\t `${GETTEXT} 'CONFIGURING IIOP CLUSTER IN APPLICATION SERVER INSTANCES...'`"
#Check if the file is created if not bail out could be that /var/tmp is write 
#protected. 
if [ ! -f /var/tmp/clsetupinstance ]
then
	WriteToLog "`${GETTEXT} 'This configuration script creates a temporary file'`"
	WriteToLog "`${GETTEXT} 'under /var/tmp. Please make sure that your /var/tmp directory'`"
	WriteToLog "`${GETTEXT} 'is available and is writable. Please re run this script'`"
	WriteToLog "`${GETTEXT} 'after verifying the same.'`"
	exit ${CLSETUP_ERROR_CREATE_TMPFILE}
fi
${RM} -f /var/tmp/iiopclustercmds
${RM} -f /var/tmp/iioplisteners


#First collect all the iiop listeners
while
	read line 
do
	instancename=`${ECHO} $line | ${CUT} -f1 -d ":"`
	adminuser=`${ECHO} $line | ${CUT} -f2 -d ":"`
	hostname=`${ECHO} $line | ${CUT} -f3 -d ":"`
	if [ ${hostname} = "localhost" ]
	then
		hostname="`hostname`"
	fi
	adminport=`${ECHO} $line | ${CUT} -f4 -d ":"`
	domainname=`${ECHO} $line | ${CUT} -f5 -d ":"`
	instanceport=`${ECHO} $line | ${CUT} -f6 -d ":"`


	WriteToLog " "
	WriteToLog "\t\t `${GETTEXT} 'Listing iiop listeners for instance'` ${instancename}"
	CMD="${ASADMIN} list-iiop-listeners --user ${adminuser} --passwordfile ${PASSWORDFILE} --host ${hostname} --port ${adminport} ${instancename}"
	WriteToLog " "
	WriteToLog "\t\t $CMD"
	WriteToLog " "
	${RM} -f /var/tmp/iioplisteners
	$CMD 1>>/var/tmp/iioplisteners 2>>${LOGFILE}
	if [ $? = 0 ]
	then
#Generate the iiop cluster config command for each iiop listener
  	  for iioplistener in `cat /var/tmp/iioplisteners`
          do 
		   GETPORTCMD="${ASADMIN} get --user ${adminuser} --passwordfile ${PASSWORDFILE} --host ${hostname} --port ${adminport} ${instancename}.iiop-listener.${iioplistener}.port " 
#echo DEBUG ${GETPORTCMD}
		   iiopendpointport="`${GETPORTCMD} |  cut -f 2 -d '='`"
#echo DEBUG ${iiopendpointport}
		   CMD="${ASADMIN} add-iiop-cluster-endpoint --iiopserverinstance ${instancename} --iiopendpointhost ${hostname} --iiopendpointport ${iiopendpointport} "
		   echo ${CMD} >> /var/tmp/iiopclustercmds	            
       	  done
	else
	   WriteToLog " "
	   WriteToLog "\t\t `${GETTEXT} 'Error in getting iiop listeners from instance ' ${instancename} `"
	fi
done < /var/tmp/clsetupinstance

#Now configure the iiop cluster in each instance 
endpointprefix="iiopclusterep"
while
	read line 
do
	endpointid=1
	instancename=`${ECHO} $line | ${CUT} -f1 -d ":"`
	adminuser=`${ECHO} $line | ${CUT} -f2 -d ":"`
	hostname=`${ECHO} $line | ${CUT} -f3 -d ":"`
	if [ ${hostname} = "localhost" ]
	then
		hostname="`hostname`"
	fi
	adminport=`${ECHO} $line | ${CUT} -f4 -d ":"`
	domainname=`${ECHO} $line | ${CUT} -f5 -d ":"`
	instanceport=`${ECHO} $line | ${CUT} -f6 -d ":"`

	CMD="${ASADMIN} delete-iiop-cluster-endpoint --user ${adminuser} --passwordfile ${PASSWORDFILE} --host ${hostname} --port ${adminport} --instance ${instancename}"
	echo 'y' | $CMD 1>>${LOGFILE} 2>>${LOGFILE}
	if [ $? = 0 ]
	then
	  WriteToLog "\t\t `${GETTEXT} 'Deleted iiop cluster endpoint '` for ${instancename} "
	else
	  WriteToLog "\t\t `${GETTEXT} 'Deleting iiop cluster endpoint failed  '` for ${instancename} "
	  WriteToLog "\t\t `${GETTEXT} 'Command failed : '` ${CMD} "
	  WriteToLog "\t\t `${GETTEXT} 'Skipping iiop cluster configuration  '` for ${instancename} "
	fi

	  while 
	  	read  iiopclustercmd 
          do 
		   CMD="${iiopclustercmd} --user ${adminuser} --passwordfile ${PASSWORDFILE} --host ${hostname} --port ${adminport} --instance ${instancename} ${endpointprefix}${endpointid}" 
		   $CMD 1>>${LOGFILE} 2>>${LOGFILE}
		   if [ $? = 0 ]
		   then
	   		WriteToLog "\t\t `${GETTEXT} 'Successfully added iiop cluster endpoint '` for ${instancename} "
		   else
	   		WriteToLog "\t\t `${GETTEXT} 'Adding iiop cluster endpoint failed  '` for ${instancename} "
		   fi
			
		   endpointid=`expr ${endpointid} + 1`
    	  done < /var/tmp/iiopclustercmds
# Reconfigure the server with the changes
	CMD="${ASADMIN} reconfig -u ${adminuser} --passwordfile ${PASSWORDFILE}  --host ${hostname} --port ${adminport} ${instancename}"
	$CMD 1>>${LOGFILE} 2>>${LOGFILE}
	if [ $? = 0 ]
	then
		WriteToLog "\t\t `${GETTEXT} 'Successfully reconfigured instance'` ${instancename}."
	else
		WriteToLog "\t\t `${GETTEXT} 'Could not reconfigure instance'` ${instancename}."
		WriteToLog "\t\t `${GETTEXT} 'Please set it through asadmin command : '` $CMD"
	fi
done < /var/tmp/clsetupinstance
${RM} -f /var/tmp/clsetupinstance
${RM} -f /var/tmp/iiopclustercmds 
}

DeleteIIOPCluster() 
{
${AWK} -f ${AWKFILE} SECTIONNAME="[INSTANCES]" ${INSTANCEFILE} > /var/tmp/clsetupinstance
if [ ! -f /var/tmp/clsetupinstance ]
then
	WriteToLog "`${GETTEXT} 'This configuration script creates a temporary file'`"
	WriteToLog "`${GETTEXT} 'under /var/tmp. Please make sure that your /var/tmp directory'`"
	WriteToLog "`${GETTEXT} 'is available and is writable. Please re run this script'`"
	WriteToLog "`${GETTEXT} 'after verifying the same.'`"
	exit ${CLSETUP_ERROR_CREATE_TMPFILE}
fi
while
	read line 
do
	instancename=`${ECHO} $line | ${CUT} -f1 -d ":"`
	adminuser=`${ECHO} $line | ${CUT} -f2 -d ":"`
	hostname=`${ECHO} $line | ${CUT} -f3 -d ":"`
	if [ ${hostname} = "localhost" ]
	then
		hostname="`hostname`"
	fi
	adminport=`${ECHO} $line | ${CUT} -f4 -d ":"`
	domainname=`${ECHO} $line | ${CUT} -f5 -d ":"`
	instanceport=`${ECHO} $line | ${CUT} -f6 -d ":"`

	CMD="${ASADMIN} delete-iiop-cluster-endpoint --user ${adminuser} --passwordfile ${PASSWORDFILE} --host ${hostname} --port ${adminport} --instance ${instancename}"
	echo 'y' | $CMD 1>>${LOGFILE} 2>>${LOGFILE}
	if [ $? != 0 ]
	then
	  WriteToLog "\t\t `${GETTEXT} 'Deleting iiop cluster endpoint failed  '` for ${instancename} "
	  WriteToLog "\t\t `${GETTEXT} 'Command failed : '` ${CMD} "
	  WriteToLog "\t\t `${GETTEXT} 'Skipping iiop cluster configuration  '` for ${instancename} "
	fi
# Reconfigure the server with the changes
	CMD="${ASADMIN} reconfig -u ${adminuser} --passwordfile ${PASSWORDFILE}  --host ${hostname} --port ${adminport} ${instancename}"
	$CMD 1>>${LOGFILE} 2>>${LOGFILE}
	if [ $? = 0 ]
	then
		WriteToLog "\t\t `${GETTEXT} 'Successfully reconfigured instance'` ${instancename}."
	else
		WriteToLog "\t\t `${GETTEXT} 'Could not reconfigure instance'` ${instancename}."
		WriteToLog "\t\t `${GETTEXT} 'Please set it through asadmin command : '` $CMD"
	fi
done < /var/tmp/clsetupinstance
${RM} -f /var/tmp/clsetupinstance
}

#This method Configures the cluster-id property in persistence-store element. 
#This gets called from CreateInstances and the instance information are passed
#as arguments to this script.
SetClusterId()
{ 
CLUSTERID="`${AWK} -f ${AWKFILE} SECTIONNAME="[CLUSTER_ID]" GETPROPERTY="cluster_id" ${RESOURCEFILE}`"
CMD="${ASADMIN} set --user ${1} --passwordfile ${PASSWORDFILE} --host ${2} --port ${3}  ${4}.availability-service.persistence-store.property.cluster-id=${CLUSTERID}"
$CMD 1>>${LOGFILE} 2>>${LOGFILE}
if [ $? = 0 ]
then
	WriteToLog "\t\t `${GETTEXT} 'cluster-id  set to '${CLUSTERID}' for instance'` ${4}"
else
	WriteToLog "\t\t `${GETTEXT} 'Could not set cluster-id for instance'` ${4}"
	WriteToLog "\t\t `${GETTEXT} 'Please set it through asadmin or cladmin.'`"
	WriteToLog "\t\t `${GETTEXT} 'Please set it through asadmin command : '` $CMD"
fi
WriteToLog " "
WriteToLog " "
WriteToLog " "
}

#This will verify the homogeneity of the cluster instances
VerifyCluster()
{
#Read the instance information file and use password file to create instances
${AWK} -f ${AWKFILE} SECTIONNAME="[INSTANCES]" ${INSTANCEFILE} > /var/tmp/clsetupinstances

${AWK} -f ${AWKFILE} SECTIONNAME="[INSTANCES]" GETMASTER=true ${INSTANCEFILE} > /var/tmp/clsetupmasterinstance

${AS_JAVA}/bin/java -Djava.library.path=$AS_INSTALL/lib:$AS_ICU_LIB -Dcom.sun.aas.defaultLocale=$AS_LOCALE -Dcom.sun.aas.icuLib=$AS_ICU_LIB -Dcom.sun.aas.webServicesLib=$AS_WEBSERVICES_LIB -Dcom.sun.aas.javaRoot=$AS_JAVA -Dcom.sun.aas.imqLib=$AS_IMQ_LIB -Dcom.sun.aas.imqBin=$AS_IMQ_BIN -Dcom.sun.aas.perlRoot=$AS_PERL -Dcom.sun.aas.configRoot=$AS_CONFIG -Dcom.sun.aas.installRoot=$AS_INSTALL -Dcom.sun.aas.domainsRoot=$AS_DEF_DOMAINS_PATH -cp $AS_INSTALL/lib/appserv-admin.jar:$AS_INSTALL/lib/appserv-ext.jar:$AS_INSTALL/lib/appserv-rt.jar:$AS_HADB/lib/hadbjdbc4.jar com.iplanet.ias.admin.clusterverifier.ClusterVerifier /var/tmp/clsetupmasterinstance /var/tmp/clsetupinstances ${PASSWORDFILE} $$
VERIFY_CLUSTER_RET="$?"


${RM} -f /var/tmp/clsetupmasterinstance

}


RestartInstances()
{
#Read the instance information file and use password file to create instances
${AWK} -f ${AWKFILE} SECTIONNAME="[INSTANCES]" ${INSTANCEFILE} > /var/tmp/clsetupinstance
WriteToLog " "
WriteToLog " "
WriteToLog "\t `${GETTEXT} 'RESTARTING APPLICATION SERVER INSTANCES...'`"
#Check if the file is created if not bail out could be that /var/tmp is write 
#protected. 
if [ ! -f /var/tmp/clsetupinstance ]
then
	WriteToLog "`${GETTEXT} 'This configuration script creates a temporary file'`"
	WriteToLog "`${GETTEXT} 'under /var/tmp. Please make sure that your /var/tmp directory'`"
	WriteToLog "`${GETTEXT} 'is available and is writable. Please re run this script'`"
	WriteToLog "`${GETTEXT} 'after verifying the same.'`"
	exit ${CLSETUP_ERROR_CREATE_TMPFILE}
fi

while
	read line 
do
	instancename=`${ECHO} $line | ${CUT} -f1 -d ":"`
	adminuser=`${ECHO} $line | ${CUT} -f2 -d ":"`
	hostname=`${ECHO} $line | ${CUT} -f3 -d ":"`
	adminport=`${ECHO} $line | ${CUT} -f4 -d ":"`
	domainname=`${ECHO} $line | ${CUT} -f5 -d ":"`
	instanceport=`${ECHO} $line | ${CUT} -f6 -d ":"`


	CMD="${ASADMIN} reconfig -u ${adminuser} --passwordfile ${PASSWORDFILE}  --host ${hostname} --port ${adminport} ${instancename}"
	WriteToLog "\t\t $CMD"
	WriteToLog " "
	$CMD 1>>${LOGFILE} 2>>${LOGFILE}
	WriteToLog "\t\t `${GETTEXT} 'Stopping the instance. '`"
	CMD="${ASADMIN} stop-instance --user ${adminuser} --passwordfile ${PASSWORDFILE} --host ${hostname} --port ${adminport} --domain ${domainname} ${instancename}"
	WriteToLog " "
	WriteToLog "\t\t $CMD"
	WriteToLog " "
	$CMD 1>>${LOGFILE} 2>>${LOGFILE}
	WriteToLog "\t\t `${GETTEXT} 'Restarting the instance. '`"
	CMD="${ASADMIN} start-instance --user ${adminuser} --passwordfile ${PASSWORDFILE} --host ${hostname} --port ${adminport} --domain ${domainname} ${instancename}"
	WriteToLog " "
	WriteToLog "\t\t $CMD"
	WriteToLog " "
	$CMD 1>>${LOGFILE} 2>>${LOGFILE}
done < /var/tmp/clsetupinstance
${RM} -f /var/tmp/clsetupinstance
}

ShowUsage()
{
	${ECHO} "`${GETTEXT} 'Usage : clsetup [--help] [--instancefile <Instance File>] [--resourcefile <Resource File>] [--passwordfile <Password File>]'`"
	${ECHO} "`${GETTEXT} '        clsetup [--help] [--instancefile <Instance File>] [--passwordfile <Password File>] --verify'`"
	${ECHO} "`${GETTEXT} '        --instancefile : absolute path of instances configuration file, default will be taken if not provided '`"
	${ECHO} "`${GETTEXT} '        --passwordfile : absolute path of password file, default will be taken if not provided '`"
	${ECHO} "`${GETTEXT} '        --resourcefile : absolute path of rersources configuration file, default will be taken if not provided '`"
	${ECHO} "`${GETTEXT} '                         This option is not neccessary when verification option is chosen '`"
	${ECHO} "`${GETTEXT} '        --verify       : No value should be provided for this option. When invoked with this option, only verification of the cluster is performed.'`"
}

CanVerify() 
{
	if [ ! -f "${AS_INSTALL}/lib/dtds/sun-server_1_2.dtd" ]
	then
		${ECHO} "`${GETTEXT} 'By default, verifcation cannot be run from the remote administration client.'`"
		${ECHO} "`${GETTEXT} 'If you like to run the verification please copy sun-server_1_2.dtd from an installation that includes the server and copy it to <Installation directory>/lib/dtds/sun-server_1_2.dtd on this machine .'`"
		${ECHO} "`${GETTEXT} 'It will be possible to run verification subsequently.'`"


		exit ${CLSETUP_CLUSTER_VERIFICATION_SERVER_DTD_NOT_FOUND}
	fi
}

#The script starts here...
#CheckUser
CheckUsage $*
WriteToLog " "
WriteToLog " "
if [ "${VERIFY_CLUSTER}" = "false" ]
then
${ECHO} "`${GETTEXT} 'Sun Java System Application Server Enterprise Edition 7 2004Q2.'`" >> ${LOGFILE}
${ECHO} "`${GETTEXT} 'Cluster Configuration Program Log.'`" >> ${LOGFILE}
WriteToLog " "
${ECHO} "#####################################################################" >> ${LOGFILE}
${ECHO} "`${GETTEXT} 'Cluster Setup Script. Execution start time'` `${DATE} +%D` `${DATE} +%H:%M:%S`"  >> ${LOGFILE}
${ECHO} "#####################################################################" >> ${LOGFILE}
ShowWelcome
else
${ECHO} "`${GETTEXT} 'Sun Java System Application Server Enterprise Edition 7 2004Q2.'`" >> ${LOGFILE}
${ECHO} "`${GETTEXT} 'Cluster Verification Program Log.'`" >> ${LOGFILE}
WriteToLog " "
${ECHO} "#####################################################################" >> ${LOGFILE}
${ECHO} "`${GETTEXT} 'Cluster verification script. Execution start time'` `${DATE} +%D` `${DATE} +%H:%M:%S`"  >> ${LOGFILE}
${ECHO} "#####################################################################" >> ${LOGFILE}
${ECHO} "`${GETTEXT} 'Welcome to Sun Java System Application Server Enterprise Edition 7 2004Q2'`"
${ECHO} "`${GETTEXT} 'Cluster Verification Program.'`"
${ECHO} "`${GETTEXT} 'Make sure that the admin server is up and running for all the domains that are present in this cluster.'`"
fi
WriteToLog " "
WriteToLog "\t `${GETTEXT} 'Running with the following Settings.'`"
WriteToLog "\t -------------------------------------------------"
WriteToLog "\t `${GETTEXT} 'Instance file'` -> ${INSTANCEFILE}"
if  [ "${VERIFY_CLUSTER}" = "false" ]
then 
WriteToLog "\t `${GETTEXT} 'Resource file'` -> ${RESOURCEFILE}"
fi
WriteToLog "\t `${GETTEXT} 'Password file'` -> ${PASSWORDFILE}"
CheckAsadmin
CheckHadbm
if [ "${VERIFY_CLUSTER}" = "true" ]
then
	CanVerify
	${ECHO} "`${GETTEXT} 'Cluster Verification Program Log.'`" >> ${LOGFILE}
	VERIFY_CLUSTER_RET="1"
	VerifyCluster >> ${LOGFILE}
	if [ "$VERIFY_CLUSTER_RET" = "0" ]
	then
		${ECHO} "`${GETTEXT} 'Cluster verified successfully .'`" >> ${LOGFILE}
		EndProgram ${CLSETUP_SUCCESS}
	else
		${ECHO} "`${GETTEXT} 'Cluster verification found discrepancies.'`" >> ${LOGFILE}
		EndProgram ${CLSETUP_CLUSTER_VERIFICATION_FAILED}
	fi
fi
WriteToLog "\t -------------------------------------------------"
CreateHadbdb
CreateSessionstore
CreateInstances
CreateIIOPCluster
RestartInstances
EndProgram ${CLSETUP_SUCCESS}
