#!/sbin/sh
#
# Copyright (c) 1998 by Sun Microsystems, Inc.
# All rights reserved.
#
#ident	"@(#)savecore	1.5	98/06/15 SMI"

#
# mksavedir
# Make sure that $DUMPADM_SAVDIR is set and exists.
#
mksavedir ()
{
	[ -z "$DUMPADM_SAVDIR" ] && DUMPADM_SAVDIR=/var/crash/`uname -n`
	[ -d "$DUMPADM_SAVDIR" ] || /usr/bin/mkdir -m 0700 -p $DUMPADM_SAVDIR
}

#
# We haven't run savecore on a dump device yet
#
savedev=none

#
# If we previously crashed early in boot before dumpadm was used to configure
# an alternate dump device, then the dump is in the primary swap partition,
# which was configured as the dump device by the first swapadd early in boot.
# Thus before we run dumpadm to configure the dump device, we first run
# savecore to check the swap partition for a dump.
#
if [ -x /usr/bin/savecore ]; then
	[ -r /etc/dumpadm.conf ] && . /etc/dumpadm.conf

	if [ "x$DUMPADM_ENABLE" != xno ] && mksavedir; then
		/usr/bin/savecore $DUMPADM_SAVDIR
		shift $#
		set -- `/usr/sbin/dumpadm 2>/dev/null | /usr/bin/grep 'device:'`
		savedev=${3:-none}
	fi
else
	echo "WARNING: /usr/bin/savecore is missing or not executable" >& 2
fi

#
# Now run dumpadm to configure the dump device based on the settings
# previously saved by dumpadm.  See dumpadm(1m) for instructions on
# how to modify the dump settings.
#
if [ -x /usr/sbin/dumpadm ]; then
	/usr/sbin/dumpadm -u || exit 1
else
	echo "WARNING: /usr/sbin/dumpadm is missing or not executable" >& 2
	exit 1
fi

if [ -r /etc/dumpadm.conf ]; then
	. /etc/dumpadm.conf
else
	echo "WARNING: /etc/dumpadm.conf is missing or unreadable" >& 2
	exit 1
fi

#
# Now that dumpadm has reconfigured /dev/dump, we need to run savecore again
# because the dump device may have changed.  If the earlier savecore had
# saved the dump, savecore will just exit immediately.
#
if [ "x$DUMPADM_ENABLE" != xno ]; then
	if /usr/sbin/swap -l | grep "^${DUMPADM_DEVICE} " >/dev/null 2>&1; then
		#
		# If the dump device is part of swap, savecore in foreground
		# so that swap activity does not overwrite the dump.  Only run
		# savecore a second time if the device is different from the
		# swap device on which we initially ran savecore.
		#
		[ "x$savedev" != "x$DUMPADM_DEVICE" ] && \
		    mksavedir && /usr/bin/savecore $DUMPADM_SAVDIR
	else
		#
		# Otherwise savecore in background so we come up faster.
		# The dump device couldn't have been dedicated before we
		# ran dumpadm, so we must execute savecore again.
		#
		mksavedir && /usr/bin/savecore $DUMPADM_SAVDIR >/dev/null 2>&1 &
	fi
fi
