#! /usr/bin/ksh
#
# ident	"@(#)bringup.ksh	1.103	99/11/10 SMI"
#
# Copyright (c) 1996, 1998, 1999 by Sun Microsystems, Inc.
# All rights reserved.
#
# bringup
#
#	The bringup script boots up a domain identified by the
#	SUNW_HOSTNAME environment variable.
#
#	The process of booting a domain consists of:
#	- verifying the configuration and environment are correct
#	- check that no other bringup is running on this domain
#	- check that domain is powered on.
#	- check that the domain is not currently up.
#	- check and see if we need to configure the centerplane.
#	- kill the obp_helper and netcon_server running on the domain.
#	- execute domain_unlock if IDN present.
#	- execute sys_reset if we configure the centerplane.
#	- execute hpost.
#	- start a new obp_helper.
#	- start a new netcon_server.
#	- update the Starfire MIB according to new domain configuration
#
# NOTE --This command has been internationalized.  There have been
#	several changes made to output strings.  These changes have
#	been made to facilitate internationalization.  Altered strings
#	have been assigned to $I18Nechomsg.  Please leave any comments
#	and suggestions with jbeloro.
#

# Set default textdomain for I18N.
TEXTDOMAIN=SUNW_SSP export TEXTDOMAIN

# Any_other_domain_UP return values
NO_DOMAIN_IS_UP=0
A_DOMAIN_IS_UP=1

# bringup_lock lock types (defined in fad_interfaces.h):
SSP_LOCK=0
SSP_UNLOCK=1
SSP_TEST=2
SSP_TLOCK=3
BRINGUP_LOCK=9 # Not in fad_interfaces.h


lock_pid=0	# The PID of the scotty bringup_lock process.

#---------------------------------------------------------
#
# log
#
# Log a message to syslog.
# -p priority - defaults to info if not specified
# -d domain - domainname, defaults to $LOG_DOMAIN
# -f facility - defaults to local0
#
#---------------------------------------------------------
log()
{
	typeset opt
	typeset pri="info"
	typeset fac="local0"
	typeset -u PRI
	typeset dom="${LOG_DOMAIN}"

	while getopts p:d:f: opt
	do
		case "$opt" in
		p) pri=$OPTARG;;
		d) dom=$OPTARG;;
		f) fac=$OPTARG;;
		esac
		shift $(( $OPTIND - 1 ))
	done
	PRI=$pri
	logger -p $fac.$pri -t "bringup-(SUNW_HOSTNAME:${dom})" "$PRI : $@"
}

#---------------------------------------------------------
#
# check_proc_active
# Check if the given pid is the same as the given process name.
# arg1 = process name
# arg2 = process pid
#
#---------------------------------------------------------
check_proc_active()
{
	if [[ $# -ne 2 ]] ; then
		gettext "usage: check_proc_active proc_name proc_pid\n"
		return 1
	fi

	proc="$1"
	pid=$2
	if [[ ! -n "$pid" ]] ; then
		return 0
	fi

	# Use ps to see if $pid is there (use System V version of ps) .
	set `/usr/bin/ps -o args -p $pid`
	if [ $# -ge 2 ] ; then
		cmd="`basename $2`"
		case "$cmd" in
		sh|jsh|rsh|csh|ksh|rksh|bash|tclsh)
			cmd="`basename $3`"
			;;
		esac

		if [[ "$cmd" = "$proc" ]]
		then
			return 1
		fi
	fi
	return 0
}


#---------------------------------------------------------
#
# Any_other_domain_UP
# Procedure to Check if remaining domains are UP.
# Return 0 (NO_DOMAIN_IS_UP) if NO other domain is up
# (Warning: this implies it's A-OK to do a hpost -C)
# Return 1 (A_DOMAIN_IS_UP) if at least one domain is up or -Q is used.
# If in doubt, return 1 because of the consequences of a hpost -C
#
# Set a global (any_up_done) to prevent unnecessary multiple passes
# through Any_other_domain_UP() which could be quite time consuming.
#
#---------------------------------------------------------
any_up_done=0	# Has Any_other_domain_UP been called before?
any_up_rv=0	# If yes, save the answer here for the next time it's called.

Any_other_domain_UP()
{
	if [ $any_up_done -ne 0 ] ; then
		any_up_done=`expr $any_up_done + 1`
		log -p warning \
			"Any_other_domain_UP multiple passes (\#$any_up_done)"
		return $any_up_rv
	else
		any_up_done=1
	fi

	if [[ ! -s "${SSPVAR}/.ssp_private/domain_config" ]]
	then
		# Empty or nonexistant domain_config file,
		# no domains have been created
		gettext 'No domain has been created, please run the `domain_create` command first.\n'
		cleanup
		exit 1
	fi

	# On quick boots -C is not allowed.
	# Return status so that -C is not used.
	if [ "$quickboot" -eq 1 ]
	then
		return $A_DOMAIN_IS_UP
	fi

	#
	# See how many domains are created
	# domain_list will contain all domains _except_
	# the current (SUNW_HOSTNAME) domain.
	#
	domain_list=`scotty -nc 'foreach dconfig [ get_domain_config ] {
				set dom [ lindex $dconfig 0 ]
				puts $dom
			}' | grep -v "^$SUNW_HOSTNAME$"`

	# n=`scotty -nc "llength [get_domain_config]"`

	if [[ -z "$domain_list" ]]
	then
		#
		# No domain other than the current domain
		# has been created.
		#
		any_up_rv=0
		return $NO_DOMAIN_IS_UP
	fi

	#
	# More than one domain exists,
	# check if any of them is active.
	#
	sunw_hostname=$SUNW_HOSTNAME

	for domain in ${domain_list}
	do
		if [[ -z "$domain" ]]
		then
			continue
		fi
		SUNW_HOSTNAME=$domain
		export SUNW_HOSTNAME

		#
		# Is hpost running on this domain?
		#
		hpost_lockfile="${SSPVAR}/adm/${domain}/hpost.lock"
		hpost_pid=$(cat ${hpost_lockfile} 2>/dev/null)

		check_proc_active hpost "$hpost_pid"
		if [[ $? -ne 0 ]]
		then
			# Yes! hpost running
			if [[ -n "$CH_ARGS" ]]
			then
				log "$SUNW_HOSTNAME is active. hpost running"
			fi
			gettext "Another instance of hpost is in progress\n"
			SUNW_HOSTNAME=$sunw_hostname
			export "SUNW_HOSTNAME"
			/usr/bin/rm -f /tmp/temp$$
			any_up_rv=1
			return $A_DOMAIN_IS_UP
		fi

		# Ping the host, timeout after 3 seconds (bug 4102350)
		#ping $domain 3 > /dev/null 2>&1
		#if [ $? -eq 0 ]
		#then
		#	log "domain $SUNW_HOSTNAME is UP - ping"
		#	gettext 'At least one domain is active\n'
		#	SUNW_HOSTNAME=$sunw_hostname
		#	export "SUNW_HOSTNAME"
		#	/usr/bin/rm -f /tmp/temp$$
		#	any_up_rv=1
		#	return $A_DOMAIN_IS_UP
		#fi

		# Is domain active?
		check_host -qb
		val=$?
		if [[ "$val" -eq 0 ]]
		then
			# Domain $SUNW_HOSTNAME is active
			if [[ "$CH_ARGS" != "" ]]
			then
				log "domain $SUNW_HOSTNAME is active"
			fi
			gettext "At least one domain is active\n"
			SUNW_HOSTNAME=$sunw_hostname
			export "SUNW_HOSTNAME"
			/usr/bin/rm -f /tmp/temp$$
			any_up_rv=1
			return $A_DOMAIN_IS_UP

		elif [ "$val" -lt 0 ] || [ "$val" -gt 1 ]
		then
			# check_host failed--returned -1 or 255
			# To be safe, treat the same as a host being up
			if [ "$CH_ARGS" != "" ]
			then
				log "check_host $SUNW_HOSTNAME failed"
			fi
			# TRANSLATION_NOTE - %s is $SUNW_HOSTNAME
			fmt=`gettext "WARNING: check_host failed for host %s"`
			printf "$fmt\n" "$SUNW_HOSTNAME"

			SUNW_HOSTNAME=$sunw_hostname
			export "SUNW_HOSTNAME"
			/usr/bin/rm -f /tmp/temp$$
			any_up_rv=1
			return $A_DOMAIN_IS_UP

		else # Domain $SUNW_HOSTNAME is NOT active
			if [[ "$CH_ARGS" != "" ]]
			then
				log "domain $SUNW_HOSTNAME is inactive"
			fi
		fi
	done

	SUNW_HOSTNAME=$sunw_hostname
	export "SUNW_HOSTNAME"
	/usr/bin/rm -f /tmp/temp$$
	any_up_rv=0
	return $NO_DOMAIN_IS_UP
}


#---------------------------------------------------------
#
# get_bringup_lock_pid()
#
# Get the scotty bringup_lock process ID for this bringup.
# Use $lock_pid if non-zero, otherwise use ps to search for it.
# Echo the PID.
# If no scotty bringup_lock process is found, echo nothing.
#
# Bugid 4101247: look for the bringup_lock PID if not known.
#
#---------------------------------------------------------
get_bringup_lock_pid()
{
	if [[ "$lock_pid" -ne 0 ]]
	then
		echo $lock_pid
		return
	fi

	# Use ps to see if it's there (use System V version of ps) .
	/usr/bin/ps -e -o fname= -o ppid= -o pid= -o args= \
		|awk '/bringup_lock/ && $1 == "scotty" && $2 == '$$' {
print $2; exit}'
}


#---------------------------------------------------------
#
# cleanup
# Procedure to clean up bringup when a signal is received.
#
# Kill hpost and bringup_lock processes when present.
#
# Note: Sometimes the bringup_lock process is already
# gone by the time we get here (e.g., it's gone for SIGINT,
# but still there when SIGTERM is used).
#
# Bugid 4101247: look for the bringup_lock PID if not known.
#
#---------------------------------------------------------
cleanup()
{
	# kill hpost if appropriate
	if [[ -f "${SSPVAR}/adm/${SUNW_HOSTNAME}/hpost.lock" ]]
	then
		hpost_pid=$(cat ${SSPVAR}/adm/${SUNW_HOSTNAME}/hpost.lock)
		kill -TERM $hpost_pid > /dev/null 2>&1
		/usr/bin/rm -f ${SSPVAR}/adm/${SUNW_HOSTNAME}/hpost.lock
	fi

	# See if there's a bringup_lock
	if [[ "$lock_pid" == "" || "$lock_pid" -eq 0 ]]
	then
		lock_pid=$(get_bringup_lock_pid)
	fi

	# Kill the process holding the lock for bringup
	if [[ "$lock_pid" != "" && "$lock_pid" -ne 0 ]]
	then
		kill -TERM $lock_pid > /dev/null 2>&1
	fi

	log "BRINGUP TERMINATED!!"

	gettext 'bringup: Terminated!!\n'
	exit 1
}


#---------------------------------------------------------
#
# getLock
# Procedure to obtain the bringup.lock file
#
#---------------------------------------------------------
getLock()
{
	ans=$(scotty -nc "bringup_lock $SSP_TEST")
	if [[ "$ans" -eq 0 ]]
	then
		# Go ahead, grab the lock
		# (note: signals KILL/STOP cannot be trapped)
		trap "cleanup" INT HUP TERM QUIT PWR URG
		scotty -nc "bringup_lock $BRINGUP_LOCK" &
		lock_pid=$!

		#
		# Fix the problem with another bringup getting
		# the lock before the background task can be started
		#
		sleep 10
		check_proc_active scotty ${lock_pid}
		if [ $? -eq 0 ] ; then
			lock_pid=0
		fi
		return $lock_pid

	else
		# This call blocks till lock is released by another bringup
		# client
		gettext 'Another instance of bringup is configuring the centerplane,\nor the hpostdump command may be running instead.\n'
		gettext 'Waiting for this operation to complete...'
		scotty -nc "bringup_lock $SSP_LOCK"
		echo ""
		return 0
	fi
}


#---------------------------------------------------------
#
# getSelection
# Procedure to get a Y(es) or N(o) answer from the user
#
#---------------------------------------------------------
getSelection()
{
	# TRANSLATION_NOTE - The following are ksh-glob patterns for "yes"
        # and "no" when entered at the keyboard.  The glob is compared
        # against the user input using the ksh [[ x == y ]] evaluation.
	# The input will be converted entirely to lower case before this
	# comparision is done (using whatever the locale-specific case
	# conversion rules are.)  The default patterns (C locale) match any
        # input containing the lower case "y" or lower case "n". (For "yes"
	# and "no", respectively.)
	typeset yes_pattern=`gettext "*y*"`
	typeset no_pattern=`gettext "*n*"`
	# Translate answer to lower case, hopefully ksh follows the
	# rules for I18N.
	typeset -l selection
	while true
	do
		read selection
		if [[ "$selection" == $yes_pattern  ]]
		then
			return 0
		elif [[ "$selection" == $no_pattern ]]
		then
			return $A_DOMAIN_IS_UP
		else
			gettext "Please enter y (yes) or n (no) "
		fi
	done
}


#---------------------------------------------------------
# IDN - BEGIN
#
#---------------------------------------------------------
# valid_os_version - IDN support routine to determine OS
#		     version of the respective domain so
#		     we can verify it supports IDN before we
#		     attempt an IDN operation.
#		     This is true if the OS version is >= 2.6
#
#---------------------------------------------------------
valid_os_version()
{
	if [ $# -ne 1 ] ; then
		gettext "usage: valid_os_version hostname\n"
		cleanup
		exit 1
	fi

	rv=0
	host=$1
	domain_entry=`scotty -nc 'foreach dconfig [ get_domain_config ] {
					puts $dconfig
				}' | grep "^{$host}"`

	if [[ ! -z "$domain_entry" ]]
	then
		set $domain_entry
		if [[ $# -ge 6 ]]
		then
			os_ver=`echo $4 | sed -e 's/{//g' -e 's/}//g'`
			if [[ ! -z "$os_ver" ]]
			then
				maj=`echo $os_ver | cut -d. -f1`
				min=`echo $os_ver | cut -d. -f2`

				#
				# Verify version is >= 2.6
				#
				if [[ "$maj" -ge 3 ]]
					then # >= 3.x is OK (bug 4106834)
					rv=1
				elif [[ "$maj" -eq 2 && "$min" -ge 6 ]]
				then
					rv=1
				fi
			fi
		fi
	fi

	return $rv
}


#---------------------------------------------------------
#
# setup_IDN()
# Perform tasks required to setup IDN.
#
#---------------------------------------------------------
setup_IDN()
{
	#
	# We have the bringup lock with respect to the given domain.
	# The domain may possibly be a member of a IDN Network.
	# Need to unlink him before proceeding with bringup.
	# First verify we're executing within the context of a
	# domain that is running a supporting OS version, otherwise
	# we'll never locate the domain_unlink command.
	#
	valid_os_version $SUNW_HOSTNAME
	valid_idn=$?

	if [[ $valid_idn -ne 0 ]]
	then
		if [[ $verbose -ne 0 ]]
		then
			vopt=-v
		else
			vopt=
		fi
		if [[ $cplane_config_on -eq 0 ]]
		then
			Copt=
		else
			Copt=-C
		fi
		if [[ $force -eq 0 ]]
		then
			fopt=
		else
			fopt=-f
		fi

		# TRANSLATION_NOTE: %s is domain name, i.e. $SUNW_HOSTNAME
		fmt=`gettext "Checking %s IDN configuration..."`
		printf "$fmt" "$SUNW_HOSTNAME"
		rv=16		# EBUSY
		i=0
		while [[ $rv -eq 16 ]]
		do
			idnopts="-E $vopt $fopt -B -XM $Copt"
			domain_unlink $idnopts $SUNW_HOSTNAME > /tmp/unlink$$ 2>&1
			rv=$?
			if [[ $rv -eq 16 ]]
			then
				if [[ $i -eq 0 ]]
				then
					gettext "busy\n"
					gettext "Another IDN operation is in progress.  Waiting..."
				else
					echo ".\c"
				fi
			fi
			i=$(( $i + 1 ))
			sleep 3
		done
	fi

	if [[ $rv -ne 0 && $rv -ne 2 ]]
	then
		#
		# Exit value of "2" indicates domain does not support IDN.
		# Treat as though successful.  No need to report to user.
		#
		gettext "error\n"
		# TRANSLATION_NOTE - %s is domain name, i.e. $SUNW_HOSTNAME
		fmt=`gettext "domain_unlink failed for host %s - retry manually"`
		printf "$fmt\n" "$SUNW_HOSTNAME"
		gettext 'domain_unlink(1M) output follows:\n'
		echo "-------------------------------------------"
		cat /tmp/unlink$$
		echo "-------------------------------------------"
		log -p warning "domain_unlink() failed"
		rm -f /tmp/unlink$$
		cleanup
		exit 1
	fi

	gettext 'done\n'
	rm -f /tmp/unlink$$
}

#
# IDN - END
#---------------------------------------------------------


#---------------------------------------------------------
#
#	Bringup starts here.
#
#---------------------------------------------------------

#
# Test SSP environment variables
#
# I've added in reasonable defaults, so users can run this command
# without sourcing ~ssp/.cshrc.  They still need to set their environment
# variable for SUNW_HOSTNAME, though.
#
SSPOPT=${SSPOPT:-/opt/SUNWssp}		export SSPOPT
SSPETC=${SSPETC:-/etc/opt/SUNWssp}	export SSPETC
SSPVAR=${SSPVAR:-/var/opt/SUNWssp}	export SSPVAR

if [[ -z "${SUNW_HOSTNAME}" ]]
then
	gettext "No SUNW_HOSTNAME environment variable. Cannot proceed.\n"
	exit 9
fi

LOG_DOMAIN="${SUNW_HOSTNAME}"

#
# Check that the SUNW_HOSTNAME has been configured.
#
domain_status | grep "^$SUNW_HOSTNAME[ 	]" >/dev/null 2>&1
if [[ $? -ne 0 ]]
then
    	# TRANSLATION_NOTE - %s is SUNW_HOSTNAME, i.e. domain name
	fmt=`gettext "SUNW_HOSTNAME %s is not configured.  Exiting."`
	printf "$fmt\n" "$SUNW_HOSTNAME"
	gettext 'bringup: Terminated!!\n'
	exit 1
fi


#
# Check that no other bringup command is running; otherwise exit.
#
if [[ ! -d "${SSPVAR}/pids" ]]
then
	mkdir -p ${SSPVAR}/pids
fi
if [[ -d "${SSPVAR}/pids" ]]
then
	touch ${SSPVAR}/pids/bringup-${SUNW_HOSTNAME}.pid
else
    	# TRANSLATION_NOTE - %s is directory name of pid directory
	fmt=`gettext "Cannot proceed.  Cannot create directory: %s"`
	printf "$fmt\n" "${SSPVAR}/pids"
	gettext 'bringup: Terminated!!\n'
	exit 1
fi

bringupid=$(cut -d' ' -f1 ${SSPVAR}/pids/bringup-${SUNW_HOSTNAME}.pid)

check_proc_active bringup "$bringupid"
if [[ $? -ne 0 ]]
 then
	gettext "Another instance of bringup for this domain is running, exiting!\n"
	gettext 'bringup: Terminated!!\n'
	exit 1
fi

#
# Put our PID in the bringup-${SUNW_HOSTNAME}.pid file.
#
echo "$$ bringup" > ${SSPVAR}/pids/bringup-${SUNW_HOSTNAME}.pid

#
# Lock bringup.lock resource
#
lock_pid=0
while [[ "$lock_pid" -eq 0 ]]
do
	getLock
	sleep 1
done


#
# Command-line argument defaults
#
POSTARGS=""; verbose=0; force=0; FORCE=0; unknowns=0; unk=""
BOOTARGS=""; cplane_config=0; quickboot=0; CH_ARGS="-B"
NETCONARGS="";
resettimetozero=0
settimetonewparam=0

#
# Go through the command line arguments
# Too bad -Q[<proc>] is used -- otherwise we could getopts.
#
for a in $*
do
	# Remove all but leading two chars
	# we also want the rest of it, so we do it backwards
	opt="${a#??}"
	arg="${a%%${opt}}"
	case $arg in
	-B)
		# Internal use, send info messages to domain's log
		CH_ARGS="-B"
		;;
	-a)
		# run post's alternate (failure recovery) diagnostic mode
		POSTARGS="${POSTARGS} -a"
		;;
	-v)
		verbose=1
		POSTARGS="${POSTARGS} -v70"
		;;
	-f)
		# skip check for domain UP|DOWN
		force=1
		;;
	-F)
		# used by automatic recovery scripts
		FORCE=1;
		;;
	-g)
		# This is strictly for POST to maintain a log file.
		POSTARGS="${POSTARGS} -g${opt}"
		;;
	-p)
		pnum="$opt"
		POSTARGS="${POSTARGS} -p${pnum}"
		;;
	-J)
		# Jam requested bus config with minimal testing.
		jammer="$opt"
		POSTARGS="${POSTARGS} -J${jammer}"
		;;
	-L)
		# This has hpost send everything to syslog.
		POSTARGS="${POSTARGS} -s";
		;;
	-Q)
		# quick reboot, used by automatic recovery scripts
		proc="$opt"
		if [[ -z "${proc}" ]]
		then
			platf=$(cut -d: -f1 ${SSPVAR}/.ssp_private/cb_config)
			proc=$(cat ${SSPVAR}/etc/${platf}/${SUNW_HOSTNAME}/bootproc)
		fi
		if [[ -z "${proc}" ]]
		then
			gettext "Cannot find bootprocessor for -Q option. Exiting.\n"
			cleanup
			exit 1
		fi
		if [[ "$cplane_config" -eq 1 ]]
		then
			gettext "Error: Cannot combine -C with -Q option. Exiting.\n"
			cleanup
			exit 1
		fi

		quickboot=1
		POSTARGS="${POSTARGS} -Q${proc}";
		;;
	-l)
		# This is used to have hpost send everything to syslog.
		level="$opt"
		POSTARGS="${POSTARGS} -l${level}";
		;;
	-C)
		# Have hpost do initial centerplane configuration.
		if [[ "$quickboot" -eq 1 ]]
		then
			gettext "Error: Cannot combine -C with -Q option. Exiting.\n"
			cleanup
			exit 1
		fi
		cplane_config=1
		;;
	-X)
		# Have hpost look at a different blacklist file.
		blacklistfile="$opt"
		POSTARGS="${POSTARGS} -X${blacklistfile}"
		;;
	*)
		# assumed boot args. These must be handed to obp_helper.
		case ${a} in
			# known args to obp_helper... just pass them on
		-D | -A | on | off )
			BOOTARGS="${BOOTARGS} ${a}"
			;;
		-rt)
			# This is used to reset the domain's time offset 
			# to zero.  This will synch the domain's time 
			# with that of the SSP.
			resettimetozero=1
			;;
		-S)
			# This is to suppress netcon session logging 
			# (for rfe 4108028)
			# Argument changed from -s to -S
			# (for bug 4221369)
			NETCONARGS="${NETCONARGS} -S"
			;;
		-st)
			# This is used to set the domain's time offset 
			# to the specified time/date.  Upon booting, the
			# domain will have the specified time/date.
			# Grab everything after the "-st" string.
			# Get rid of preceeding spaces.
			# Get rid of subsequent parameters.
			# All that is left is the time/date.
			newdatetime=`echo -st $* | \
				sed -e 's/\(.*\)-st\(.*\)/\2/'  \
				-e 's/^ //' -e \
				-e 's/\(.*\) \(.*\)/\1/'`
			x=$(printf "%012.0f\n" $newdatetime 2>/dev/null)
			x=$(printf "%012.0f\n" $x 2>/dev/null)
			if [[ $newdatetime = $x ]]
			then 
				settimetonewparam=1
			else 
				gettext "Error: Invalid parameter for -st\n"
				cleanup
				exit 1
			fi
			;;
		*)
			# unknown argument.
			# keep track of them and append them after an --
			# to obp_helper (it's using optarg and just
			# doesn't know any better
			unk="${unk} ${a}"
			unknowns=1
		esac

		;;
	esac
done

cplane_config_on=0

if [[ ${unknowns} -ne 0 ]]
then
	# 4029290: bringup shouldn't pass boot args when -A off is used
	if [[ "${BOOTARGS}" != *"-A off"* ]]
	then
	    unk="boot ${unk}"
	    BOOTARGS="${BOOTARGS} ${unk}"
	fi
fi

#
# Arguments were processed OK--log message that we started.
#
if [[ "$CH_ARGS" != "" ]]
then
	log "BRINGUP COMMAND STARTED"
fi

#
# Verify the SNMP and CBE are OK (bugid 4116566)
#
ans=`scotty -nc "ProbeSspMib"`
if [[ "$ans" != "0" ]]
then
	gettext "Cannot read CBE information from snmpd.\n"
	gettext "Check log and try again.  Exiting.\n"
	cleanup
	exit 1
fi

#
# Check that domain is powered ON
# NOTE: -F means it comes from automatic recovery scripts
#
if [[ "$FORCE" -eq 0 && "$force" -eq 0 ]]
then
	power -v -q
	status=$?
	if [[ $status -eq 1 ]]
	then
		if [[ "$CH_ARGS" != "" ]]
		then
			log -p notice	"domain not powered ON"
			log -p info	"BRINGUP COMMAND FINISHED"
		fi
		gettext 'Domain not fully powered, please run the `power -on` command first.\n'
		cleanup
		exit 1
	fi

	if [[ $status -ge 1 ]]
	then
		gettext "Warning: check for domain power status FAILED\n"
		Any_other_domain_UP
	fi
fi


#
# Check that domain is DOWN
# NOTE: -F means it comes from automatic recovery scripts
#
if [[ "$force" -eq 0 && "$FORCE" -eq 0 ]]
then
	check_host -q
	val=$?
	if [[ "$val" -eq 0 ]]
	then
		# Host is UP
		gettext 'WARNING: Host is active, filesystems may be corrupted.\n'
		echo
		gettext 'Do you really wish to continue (y/n)? '
		getSelection
		if [[ "$?" -eq 0 ]]
		then
			gettext 'Is this command executed because of a Hung Host (y/n)? '
			getSelection
			if [[ "$?" -eq 0 ]]
			then
				log -p notice "DOWN System Hung"
			fi
		else
			gettext "bringup: Exiting\n"
			cleanup
			exit 1
		fi
	fi

	if [[ "$val" -lt 0 || "$val" -gt 1 ]]
	then
		# TRANSLATION_NOTE - %s is $SUNW_HOSTNAME
		fmt=`gettext "WARNING: check_host failed for host %s"`
		printf "$fmt\n" "$SUNW_HOSTNAME"
		gettext 'If you wish to continue, run the command `bringup -f`\n'
		cleanup
		exit 1
	fi
fi


#
# Determine if system needs centerplane configuration. Criteria:
#	- Only one domain exists.
#	- Other domains are not being brought UP
#
if [[ "$force" -eq 0 && "$FORCE" -eq 0 ]]
then
	Any_other_domain_UP
	if [[ "$?" -eq $NO_DOMAIN_IS_UP || ( "$cplane_config" -eq 1 && "$cplane_config_on" -eq 0 ) ]]
	then
		#
		# It is safe to run -C because no domain is UP or
		# user has run bringup -C
		#
		gettext "This will configure the Centerplane. Please confirm (y/n)? "
		getSelection
		if [ "$?" -eq 0 ]
		then
			POSTARGS="${POSTARGS} -C"
			cplane_config_on=1
		else
			# Release lock
			kill -TERM $lock_pid > /dev/null 2>&1
			lock_pid=0
		fi
	fi
fi

# Check case when -f and -C are given so as to update POSTARGS
if [[ "$cplane_config" -eq 1 && "$cplane_config_on" -eq 0 && "$force" -eq 1 ]]
then
	POSTARGS="${POSTARGS} -C"
	cplane_config_on=1
fi

# Check case when only -f is given
if [[ "$force" -eq 1 && "$cplane_config" -eq 0 && "$cplane_config_on" -eq 0 ]]
then
	Any_other_domain_UP
	if [ "$?" -eq 0 ]
	then
		# It is safe to run -C because no domain is UP
		POSTARGS="${POSTARGS} -C"
		cplane_config_on=1
	fi
fi

# Check case when -F is given. Normally invoked from automatic reboot scripts.
if [[ "$FORCE" -eq 1 ]]
then
	Any_other_domain_UP
	if [[ "$?" -eq 0 && "$cplane_config_on" -eq 0 ]]
	then
		#
		# It is safe to run -C because no domain is UP or
		# user has run bringup -C
		#
		POSTARGS="${POSTARGS} -C"
		cplane_config=1
		cplane_config_on=1
	fi
fi

#
# IDN Setup
#
# IDN disabled for now (bugid 4120709)
#
#setup_IDN()


#
# Release the lock process unless we're configuring the centerplane.
#
echo $POSTARGS | grep '\-C' > /dev/null 2>&1
if [[ $? -eq 0 ]]
then
	log "configuring the centerplane, POST args ${POSTARGS}"
	ans=`scotty -nc "stopDR; resetConfMemAddrMap"`
else
	# Release lock
	if [[ "$lock_pid" -ne 0 ]]
	then
		kill -TERM $lock_pid > /dev/null 2>&1
		lock_pid=0
	fi
fi

#
# kill obp_helper and netcon_server running on this domain
#
if [[ -f "${SSPVAR}/pids/obp_helper-${SUNW_HOSTNAME}.pid" ]]
then
	obp_helper_pid=`cut -d' ' -f1 ${SSPVAR}/pids/obp_helper-${SUNW_HOSTNAME}.pid`

	check_proc_active obp_helper "${obp_helper_pid}"
	if [[ $? -ne 0 ]]
	then
		kill -KILL $obp_helper_pid > /dev/null 2>&1
	fi
fi

if [ -f "${SSPVAR}/pids/netcon_server-${SUNW_HOSTNAME}.pid" ]
then
	netcon_pid=`cut -d' ' -f1 ${SSPVAR}/pids/netcon_server-${SUNW_HOSTNAME}.pid`

	check_proc_active netcon_server "${netcon_pid}"
	if [[ $? -ne 0 ]]
	then
		kill -KILL $netcon_pid > /dev/null 2>&1
	fi
fi

#
# check for arbstop dumps that might be running
#
ans=`scotty -nc "eddpostdump_check"`
if [[ "$ans" -ne 0 ]]
then
	# A error occurred during the arbstop dump check.
	log -p warning "Could not assert the state of eddpostdump lock file"
fi

#
# Start hpost.
#
if [ "$CH_ARGS" != "" ]
then
	log "Starting: hpost ${POSTARGS}"
fi

# TRANSLATION_NOTE - text is appended with a command line (command + arguments)
starting_fmt=`gettext "Starting: %s"`
printf "$starting_fmt\n" "hpost ${POSTARGS}"
hpost ${POSTARGS}

#
# Save return value from hpost and validate it
#
bootproc=$?
if [[ "$bootproc" -lt 0 || "$bootproc" -gt 63 ]]
then
	if [[ "$CH_ARGS" != "" ]]
	then
		log -p notice	"hpost failed, exit status is $bootproc"
		log -p info	"BRINGUP COMMAND FINISHED"
	fi
	# TRANSLATION_NOTE - %d is the exit status of hpost
	fmt=`gettext "hpost FAILED - Cannot proceed, exit status=%d"`
	printf "$fmt\n" "$bootproc"
	cleanup
	exit 1
fi

#
# Release bringup.lock file if appropriate
#
if [[ "$lock_pid" -gt 0 ]]
then
	# kill process holding lock for bringup
	kill -TERM $lock_pid > /dev/null 2>&1
fi

#
# Save bootproc to file
#
platf=$(cut -d: -f1 ${SSPVAR}/.ssp_private/cb_config)
bootproc_file=${SSPVAR}/etc/${platf}/$SUNW_HOSTNAME/bootproc
touch ${bootproc_file}
# TRANSLATION_NOTE - %d is a boot processor number
printf "`gettext 'Boot processor: %d'`\n" "$bootproc"
# TRANSLATION_NOTE - %s is the pathname of the boot processor file
printf "`gettext 'Boot processor is written to %s'`\n" ${bootproc_file}
echo ${bootproc} > ${bootproc_file}
if [[ $? -eq 1 ]]
then
	# TRANSLATION_NOTE - %s is the pathname of the boot processor file
	printf "`gettext 'Could not create file: %s'`\n" ${bootproc_file}
	gettext 'bringup: Terminated!!\n'
	exit 1
else
	bootproc_test=$(cat ${bootproc_file})
	if [[ -z "$bootproc_test" ]]
	then
		# TRANSLATION_NOTE - %s is the path to the boot processor file
		printf "`gettext '%s is empty!'`\n" ${bootproc_file}
		gettext "File system might be full. Bringup exiting!\n"
		gettext 'bringup: Terminated!!\n'
		exit 1
	fi
fi

#
# Update Starfire MIB. Note: done only to the domainTable's BootProc
# and InterruptVector objects.
#
gettext "Updating the boot processor and IntVector MIB\n"
updateDTable=$(scotty -nc "updateDomainTable $SUNW_HOSTNAME $bootproc")

#
# Check if the domain's time/date has been specified and calculate offset
# from the actual time/date on the SSP.  The offset must then be stored
# in the ssp_resource file.
#
if [[ "$settimetonewparam" -eq 1 ]]
then
	xtime=$(scotty -nc "calc_domain_time_offset $newdatetime")
	scotty -nc "setDomainTimeOffset $xtime"
fi

#
# Check if the domain's time/date offset is to be reset to zero.
#
if [[ "$resettimetozero" -eq 1 ]]
then
	scotty -nc "setDomainTimeOffset 0"
fi

#
# Start obp_helper
#
if [[ "$CH_ARGS" != "" ]]
then
	log "Starting: obp_helper -m ${bootproc} ${BOOTARGS}"
fi
printf "$starting_fmt\n" "obp_helper -m ${bootproc} ${BOOTARGS}"
obp_helper -m ${bootproc} ${BOOTARGS} </dev/null 2>&1 &

#
# Start netcon_server
#
if [[ "$CH_ARGS" != "" ]]
then
	log "Starting: netcon_server -p ${bootproc} ${NETCONARGS}"
fi
printf "$starting_fmt\n" "netcon_server -p ${bootproc} ${NETCONARGS}"
netcon_server -p ${bootproc} ${NETCONARGS} &

#
# Before we exit, let's sleep to give time for dhlp to put its
# signature on the bootproc.
#
sleep 5
flag=1
for i in 1 2 3 4 5
do
	check_host -q -p $bootproc
	if [[ $? -eq 0 ]]
	then
		flag=0
		break
	else
		sleep 3
	fi
done

if [[ "$flag" -eq 1 ]]
then
	log -p warning "could not assert signature and state on bootproc"
fi

#
# Log a message and exit.
#
if [[ "$CH_ARGS" != "" ]]
then
	log "BRINGUP COMMAND FINISHED"
fi
exit 0
