# $Id: rc.update,v 1.1 1998/12/30 19:53:17 danw Exp $

# rc.update - Check if a update is in process and finish it if so.

libdir=/usr/athena/lib/update

mreboot() {
	if [ "$method" = Manual ]; then
		echo "The update to version $newvers is complete."
		echo "You may now examine the system before rebooting"
		echo "it under $newvers.  When you are finished, type"
		echo "'exit' and the system will reboot."
		echo ""
		/bin/sh
	fi
	echo "Update completed, rebooting in 15 seconds."
	sync
	sleep 15
	exec reboot
}

if [ `awk '{a=$5} END {print a}' /etc/athena/version` = Reboot ]; then
	reason=`awk '{a=$6} END {print a}' /etc/athena/version`
	method=`awk '{a=$7} END {print a}' /etc/athena/version`
	newvers=`awk '{a=$8} END {print a}' /etc/athena/version`
	version=`awk '{a=$9} END {print a}' /etc/athena/version`

	case $reason in 
	newkernel)
		case `sysctl -n machdep.booted_kernel` in
		netbsd) 
			# New-kernel reboot succeeded. Continue.
			if [ -f /netbsd.custom ]; then
				ln -f /netbsd /netbsd.custom
			fi
			;;
		netbsd-preupdate)
			# New-kernel reboot failed. Back out. 
			echo "Old kernel booted during update."
			echo "Assuming new kernel failure; backing out."
			echo "Further updates will not take place."
			echo "Please contact SIPB (netbsd-help@mit.edu"
			echo "or x3-7788) for assistance."
			mv /netbsd-preupdate /netbsd
			mv /usr/vice/etc/dkload/libafs.o-preupdate \
			   /usr/vice/etc/dkload/libafs.o
			echo "***** New kernel failed. Backing out" \
				>> /var/athena/update.log
			echo "Athena Workstation (`/bin/athena/machtype`)" \
				"Version failure $method $newvers $version" \
				"`date`" >> /etc/athena/version
			exec reboot
			;;
		*)
			# The user did something odd.
			echo "Nonstandard kernel booted during update."
			echo "Boot netbsd-preupdate to back out of failed " \
				"update."
			echo "Dropping to shell."
			/bin/sh
			;;
		esac
	
		sh /etc/athena/rc.afs

		echo "***** Continuing update after new-kernel reboot" \
			>> /var/athena/update.log
		if [ ! -r $libdir/do-update ]; then
			echo "Cannot continue partially completed update."
			echo "Please contact SIPB at netbsd-help@mit.edu"
			echo "or x3-7788. Thank you."
			exit 1
		fi
		if [ "$method" = Manual ]; then
			sh "$libdir/do-update" "$method" "$version" "$newvers" \
				2>&1 | tee -a /var/athena/update.log
		else
			sh "$libdir/do-update" "$method" "$version" "$newvers" \
				< /dev/null 2>&1 | tee -a /var/athena/update.log
		fi
		mreboot
		;;
	newos)
		sh /etc/athena/rc.afs

		echo "***** Finishing update after new-os reboot" \
			>> /var/athena/update.log
		if [ ! -r $libdir/finish-update ]; then
			echo "Cannot finish partially completed update."
			echo "Please contact SIPB at netbsd-help@mit.edu"
			echo "or x3-7788. Thank you."
			exit 1
		fi

		sh $libdir/finish-update "$newvers" \
			2>&1 | tee -a /var/athena/update.log
		mreboot
		;;
	*)
		echo "/etc/athena/version is corrupt. Not continuing update."
		exit 1
		;;
	esac

fi
