#! /usr/bin/sh
#
# ident	"@(#)ssp_upgrade.sh	1.14	98/03/04 SMI"
#
# Copyright (c) 1996 by Sun Microsystems, Inc.
# All rights reserved.
#
# Script to conclude SSP upgrade process.
#

###########################################################################
#
# ssp_pkgrm
# 
# Check for package existence before invoking pkgrm.
# argument contains a list of packages to remove
#
###########################################################################
ssp_pkgrm()
{
	while [ $# -gt 0 ]; do
		pkginfo $1 > /dev/null 2>&1
		if [ $? -eq 0 ]; then
			echo "pkgrm $1...\c" 
			pkgrm -n -a ${adminfile} $1 >> ${logfile} 2>&1
			if [ $? -ne 0 ]; then
				pkg_err=1
				echo failed
			else
				echo done
			fi
		fi
		shift
	done
}

###########################################################################
#
# ssp_pkgadd
# 
# Individually perform pkgadd. The advantage of doing it one at a time
# is that we could install even if a package on the list is missing.
# argument contains a list of packages to remove
#
###########################################################################
ssp_pkgadd()
{
	while [ $# -gt 0 ]; do
		echo "pkgadd $1...\c" 
		pkgadd -d ${package_dir} -a ${adminfile} $1 >> ${logfile} 2>&1
		if [ $? -ne 0 ]; then
			pkg_err=1
			echo failed
		else
			echo done
		fi
		shift
	done
}

###########################################################################
#
# ssp_pkgadd_ab
#
# Install the SSP 3.1 AnswerBook (SUNWuessp). It needs to be interactive.
#
###########################################################################
ssp_pkgadd_ab()
{
	while /bin/true; do
		echo "Do you want to install the SSP 3.1 AnswerBook (SUNWuessp) ? (y/n): \c"
		read A
		if [ "$A" = "y" ]; then
			pkgadd -d ${package_dir} SUNWuessp
			if [ $? -ne 0 ]; then
				pkg_err=1
				echo "pkgadd SUNWuessp failed" >> ${logfile} 2>&1
				echo "SUNWuessp package installation failed"
			fi
			break
		fi
		if [ "$A" = "n" ]; then
			break
		fi
	done
}

###########################################################################
#
# save_a_copy
# 
# Make a backup copy of a file for upgrade purpose.
#
###########################################################################
save_a_copy()
{
	while [ $# -gt 0 ]; do
		echo "copying $1 $1.__upgrade"
		cp $1 $1.__upgrade
		shift
	done
}

###########################################################################
#
# save_n_copy
# 
# save dst file before copying from src file
# $1 - dst
# $2 - src
# $3 - mode
# $4 - owner
# $5 - cp_anyway - a flag indicating if copy is needed if the file does
#		   not exist
#
###########################################################################
save_n_copy()
{
	dst=${1}
	src=${2}
	mode=${3}
	owner=${4}
	cp_anyway=${5}
	if [ -f ${dst} ]; then
		diff ${dst} ${src} > /dev/null 2>&1
		result=$?
		if [ ${result} -eq 0 ]; then
			# no copy necessary
			return
		fi
		for i in 8 7 6 5 4 3 2 1 0; do
			n=`expr ${i} + 1`
			[ -f ${dst}.${i} ] && mv -f ${dst}.${i} ${dst}.${n}
		done
		cp -f ${dst} ${dst}.0
	elif [ "${cp_anyway}" = "no" ]; then
		return
	fi
	if [ -f "${src}" ]; then
		if cp ${src} ${dst} ; then
			chmod ${mode} ${dst}
			chown ${owner} ${dst}
		else
			fatal "Couldn't create ${dst}!"
		fi
	fi
}

#############################################################################
#
# convert_domain_config
#
# Convert domain_config file to new (3.1) (IDN enhanced) format.
# old (3.0) format:	domain : platform : physical : release : boardlist
# new (3.1) format:	domain : platform : physical : release : IDNinfo : boardlist
#
#############################################################################

convert_domain_config()
{
	OLD_dc=${1}
	mode=${2}
	owner=${3}

	if [ ! -f $OLD_dc ] ; then
		echo "$OLD_dc not found"
		return
	fi

	NEW_dc=/tmp/updc$$
	> $NEW_dc

	awk 'BEGIN { 
		FS = ":";  ver = 0.0;
	} {
		if ( NF == 6 ) {
			if ( ver == 0.0 ) {
				ver = 3.1;
			} else if ( ver == 3.0 ) {
				printf("ERROR! %s has invalid format (line %d)\n", \
					FILENAME, NR);
				exit (1);
			}
			print $0 >> new_dc

		} else if ( NF == 5 ) {
			if ( ver == 0.0 ) {
				ver = 3.0;
			} else if ( ver == 3.1 ) {
				printf("ERROR! %s has invalid format (line %d)\n", \
					FILENAME, NR);
				exit (1);
			}
			printf("%s:%s:%s:%s:%s:%s\n", \
				$1, $2, $3, $4, "-1.0", $5) >> new_dc
		} else {
			printf("ERROR! %s has invalid format (line %d)\n", \
				FILENAME, NR);
			exit (1);
		}

	}' new_dc=$NEW_dc $OLD_dc

	if [ $? -ne 0 ] ; then
		/bin/rm -f $NEW_dc
		fatal "domain_config conversion"
	fi

	diff $OLD_dc $NEW_dc >/dev/null 2>&1
	if [ $? -eq 0 ] ; then
		#
		# No need to upgrade, old and new are the same.
		#
		/bin/rm -f $NEW_dc

	elif [ -f $NEW_dc ] ; then
		mv $NEW_dc $OLD_dc
		if [ $? -ne 0 ] ; then
			fatal "Couldn't create $OLD_dc"
		fi
		chmod ${mode} $OLD_dc
		chown ${owner} $OLD_dc
	fi
}

preupgrade()
{
	# If either SUNWsspue or SUNWsspdf is installed, we
	# go ahead of installing this package.
	pkginfo -l SUNWsspue | grep "VERSION:  3.0.0" > /dev/null 2>&1
	result1=$?

	pkginfo -l SUNWsspdf | grep "VERSION:  3.0.0" > /dev/null 2>&1
	result2=$?

	if [ $result1 -eq 1 -o $result2 -eq 1 ]; then
		echo "SSP 3.1 upgrade pre-processing is not required."
		return
	fi

	list="\
/export/home/ssp/.Xdefaults \
/export/home/ssp/.openwin-menu \
/export/home/ssp/.xinitrc \
/export/home/ssp/.drtclrc \
/export/home/ssp/.openwin-init \
/export/home/ssp/.openwin-menu-ssp \
/export/home/ssp/.redxrc \
/export/home/ssp/.cshrc \
/export/home/ssp/.login \
/export/home/ssp/.postrc \
/var/opt/SUNWssp/.ssp_private/bringup.lock \
/var/opt/SUNWssp/.ssp_private/bringup_dr.lock \
/var/opt/SUNWssp/.ssp_private/ssp_resource \
/var/opt/SUNWssp/adm/.logger
"
	save_a_copy $list
}

#############################################################################
#
# ssp_terminate
#
# kill all ssp deamons that might be running before installing new software.
# this added to ssp_upgrade to fix bug id 4094395.
#
#############################################################################

ssp_terminate()
{
#
# ident	"@(#)ssp_terminate.sh	1.6	97/10/14 SMI"
#
# Copyright (c) 1997 by Sun Microsystems, Inc.
# All rights reserved.
#
# killing the ssp_startup first
#
for pid in `ps -ef | /usr/bin/egrep "ssp_startup|hostview" \
		| /usr/bin/egrep -v egrep | awk '{print $2}'`
do
	#echo "$pid being killed"
	kill -KILL $pid > /dev/null 2>&1
done
#
# give time for ssp_startup to die so that it does not restart
# the daemons.
#
for pid in `ps -ef | /usr/bin/egrep "bringup|hpost|scotty|netcon|netcon_server|obp_helper" \
		| /usr/bin/egrep -v "egrep|ps \-ef|rlogin|xterm" | awk '{print $2}'`
do
	#echo "$pid being killed"
	kill -KILL $pid > /dev/null 2>&1
done
#
# killing the daemons
#
for pid in `ps -ef | /usr/bin/egrep "edd|snmpd|straps|cbs|fad" \
		| /usr/bin/egrep -v "egrep|ps \-ef|rlogin|xterm" | awk '{print $2}'`
do
	#echo "$pid being killed"
	kill -KILL $pid > /dev/null 2>&1
done
#
# killing ap daemons
#
for pid in `ps -ef | /usr/bin/egrep "ap_ssp_daemon|ap_startup" \
		| /usr/bin/egrep -v "egrep|ps \-ef|rlogin|xterm" | awk '{print $2}'`
do
	#echo "$pid being killed"
	kill -KILL $pid > /dev/null 2>&1
done
#
# killing machine_server
#
for pid in `ps -ef | /usr/bin/egrep machine_server \
		| /usr/bin/egrep -v "egrep|ps \-ef|rlogin|xterm" | awk '{print $2}'`
do
	#echo "$pid being killed"
	kill -KILL $pid > /dev/null 2>&1
done
}

#
# Beginning of ssp_upgrade
#
umask 033

# Usage: ssp_upgrade
USAGE="Usage: $0 package_dir"
SSPOPT=/opt/SUNWssp
SSPVAR=/var/opt/SUNWssp
PATH="/usr/bin:/usr/sbin"
export PATH

fatal()
{
	echo "ERROR! $*" >&2
	echo "ABORTING!" >&2
	exit 2
}
CBCONFIGFILE=${SSPVAR}/.ssp_private/cb_config

#
# If wrong arguments, print out usage and exit.
#
if [ $# -ne 1 ]; then
	echo ${USAGE}
	exit 4
fi
package_dir=$1

#############################################################################
#
# Check that the user is root
#
#############################################################################
if [ -x /usr/bin/id ]
then
	eval `id | /usr/bin/sed 's/[^a-z0-9=].*//'`
	if [ "${uid:=0}" -ne 0 ]
	then
		fatal "You must be root to run $0."
	fi
else
	fatal "$0: can't check user id."
fi

#############################################################################
#
# See if the cb_config file exists
#
#############################################################################
if [ -s ${CBCONFIGFILE} ]
then
	# how many entries in file? assuming only a single line...
	# this needs to be expanded to handle multiple entries.

	# try and parse current info
	PLATFORM_NAME=`cut -d: -f1 ${CBCONFIGFILE}`
	if [ -z "${PLATFORM_NAME}" ]; then
		fatal "Corrupted ${CBCONFIGFILE}: missing platform name"
	fi
	PLATFORM_TYPE=`cut -d: -f2 ${CBCONFIGFILE}`
	if [ -z "${PLATFORM_TYPE}" ]; then
		fatal "Corrupted ${CBCONFIGFILE}: missing platform type"
	fi
	CB0_NAME=`cut -d: -f3 ${CBCONFIGFILE}`
	CB0_STATUS=`cut -d: -f4 ${CBCONFIGFILE}`
	CB1_NAME=`cut -d: -f5 ${CBCONFIGFILE}`
	CB1_STATUS=`cut -d: -f6 ${CBCONFIGFILE}`
	if [ "${CB0_NAME}" -a "${CB0_STATUS}" = "P" -a -z "${CB1_STATUS}" ]; 
then
		PRI_CB=${CB0_NAME}
	elif [ "${CB1_NAME}" -a "${CB1_STATUS}" = "P" -a -z "${CB0_STATUS}" ]; 
then
		PRI_CB=${CB1_NAME}
	else
		fatal "Corrupted ${CBCONFIGFILE}: missing primary control board"
	fi
else
	fatal "missing cb_config file"
fi


#############################################################################
#
# Print a little intro.
#
#############################################################################
fmt << EOF

Beginning SSP upgrade...

EOF
ssp_terminate
#############################################################################
#
# Set up SSP upgrade log file
#
#############################################################################
if [ -d /var/sadm/system/logs ]; then
	logfile=/var/sadm/system/logs/ssp_upgrade_log
else
	logfile=/tmp/ssp_upgrade_log
fi

# clear log file
pkg_err=0
cat /dev/null > ${logfile}
echo "SSP software upgrade" >> ${logfile}
echo `date` >> ${logfile}
echo >> ${logfile}

#############################################################################
#
# Set up pkgadd/pkgrm admin file
#
#############################################################################
adminfile=/tmp/ssp_upgrade_adminfile.$$
cat > ${adminfile} << EOF
mail=
instance=overwrite
partial=nocheck
runlevel=nocheck
idepend=nocheck
rdepend=nocheck
space=quit
setuid=nocheck
conflict=nocheck
action=nocheck
basedir=default
EOF

#############################################################################
#
# Perform preupgrade if SSP 3.0 packages are installed.
#
#############################################################################
preupgrade

#############################################################################
#
# Remove SSP patches, if any
#
#############################################################################
patchdir=`showrev -p | egrep 'SUNWssp' | awk '{print $2}'`
if [ -d /var/sadm/patch ]; then
	chdir /var/sadm/patch
	rm -fr ${patchdir}
fi

#############################################################################
#
# Remove the rest of the packages
# SUNWsspid and SUNWsspdo are new to SSP 3.1
#
#############################################################################
ssp_pkgrm SUNWsspdr SUNWsspid SUNWssppo SUNWsspob SUNWsspdo SUNWsspr SUNWsspst SUNWsspdf SUNWsspmn SUNWsspop SUNWsspue SUNWuessp

#############################################################################
#
# Now add the new packages
#
#############################################################################
ssp_pkgadd SUNWsspue SUNWsspop SUNWsspmn SUNWsspdf SUNWsspst SUNWsspr SUNWsspdo SUNWsspob SUNWssppo SUNWsspid SUNWsspdr

# Install AnswerBook. It needs to be interactive.
ssp_pkgadd_ab

if [ $pkg_err -eq 1 ]; then
	echo "Error detected. See ${logfile} for detail."
        while /bin/true; do
                echo "Do you want to continue? (y/n): \c"
                read A
                if [ "$A" = "y" ]; then
                        break
                fi
                if [ "$A" = "n" ]; then
			echo "ABORTING!" >&2
			exit 2
                fi
        done
fi

#############################################################################
#
# Set up the tftpboot stuff.
#
#############################################################################
CBOBJS=${SSPOPT}/cbobjs
cp ${CBOBJS}/cbe.ima /tftpboot/cbe.ima
cp ${CBOBJS}/flash_boot.ima /tftpboot/flash_boot.ima
cp ${SSPVAR}/.ssp_private/cb_port /tftpboot/cb_port

#############################################################################
#
# Create /var/opt/SUNWssp/etc   /var/opt/SUNWssp/etc/${PLATFORM_NAME}
# and /var/opt/SUNWssp/etc/${PLATFORM_NAME}/cbobjs directories. Also copy
# over edd configure files for this platform.
#############################################################################

priv=${SSPVAR}/.ssp_private
tmpl=${priv}/templates/${PLATFORM_TYPE}
p_etc=${SSPVAR}/etc/${PLATFORM_NAME}
cbobjs_dir=$p_etc/cbobjs
PLATFORM_ERC_FILE=edd.platform.erc
DOMAIN_ERC_FILE=edd.domain.erc
EDD_ERC_FILE=edd.erc
EDD_EMC_FILE=edd.emc
DOMAIN_CONFIG=domain_config

# if a copy of the erc file exists, save it off 
save_n_copy ${p_etc}/${EDD_ERC_FILE} ${tmpl}/${PLATFORM_ERC_FILE} 640 ssp yes
 
# if a copy of the emc file exists, save it off 
save_n_copy ${p_etc}/${EDD_EMC_FILE} ${tmpl}/${EDD_EMC_FILE} 640 ssp  yes

#
# Update domain_config file
#
save_n_copy ${priv}/${DOMAIN_CONFIG} "" 640 ssp  yes
convert_domain_config ${priv}/${DOMAIN_CONFIG} 644 ssp

#
# Need to take care of domain erc files too
#
for i in `ls ${p_etc}`; do
	newdir=${p_etc}/${i}
	if [ -d ${newdir} ]; then
		save_n_copy ${newdir}/${EDD_ERC_FILE} ${tmpl}/${DOMAIN_ERC_FILE} 640 ssp no
	fi
done

#
# Remove globalconst.tcl and let it rebuild by edd
#
rm -f ${SSPVAR}/etc/${PLATFORM_NAME}/cbobjs/globalconst.tcl

#
# Make sure bids.tcl and thermcaldata.tcl are there
# (bugs 4054660 4067723)
touch ${cbobjs_dir}/bids.tcl
chmod 644 ${cbobjs_dir}/bids.tcl
chown ssp ${cbobjs_dir}/bids.tcl

touch ${cbobjs_dir}/thermcaldata.tcl
chmod 644 ${cbobjs_dir}/thermcaldata.tcl
chown ssp ${cbobjs_dir}/thermcaldata.tcl

#
# Remove /etc/opt/SUNWssp/snmp/*.idy and let it rebuild by scotty
#
rm -f /etc/opt/SUNWssp/snmp/*.idy

#
# Clean up and exit.
#
rm -f /.SSP_DEFAULTS
echo SSP upgrade completed.
exit 0
