#!/bin/sh

# /etc/init.d/kexec: set up kexec for in-place reboot
# 
# Kacper Wysocki, June 2005 * initial version
# August 2006: v002: init.d script inception - inspired by gentoo's
#
# Defaults to current kernel image.

#set -x
#KERNEL=""
#ROOTDEV=""
KOPTS='ro idebus=100'

#ROOTDEV=hda3
# Fancy way of getting root device :-)
test -z "$ROOTDEV" && ROOTDEV=` cat /etc/fstab | awk '{if ($2=="/") print $1}'`
if [ -z "$ROOTDEV" -o ! -b $ROOTDEV ]
	then
	echo "KEXEC ERROR : Could not detect root device through fstab. Please set the ROOTDEV variable to the devicefile for your root partition, eg. ROOTDEV=\"/dev/hda2\"."
	exit 1
fi

export PATH="${PATH:+$PATH:}/usr/sbin:/sbin"

if [ ! -r /proc/kallsyms -o -z "`cat /proc/kallsyms | grep kernel_kexec`" ]
	then
	echo "KEXEC ERROR: Could not detect kexec support in kernel. You must be running a kernel that has CONFIG_KEXEC=y."
	exit 1
fi
if [ ! -e `which kexec` ]
	then
	echo "KEXEC ERROR: No kexec tool in path. Install the kexec-tools package."
	exit 1
fi


if [ "$2" = "b" ] 
	then
	if [ -x /sbin/bootchartd ]
		then
		KOPTS="$KOPTS init=/sbin/bootchartd"
		echo -n "bootchart on "
	else
		echo "KEXEC ERROR: bootchartd not found, continuing without bootchartd"
	fi
fi

case "$1" in
	start)
		# Load the chosen kernel
		echo -n "Kexec: Loading kernel..."
		if [ -z "$KERNEL" ]
			then
			if [ -r /boot/vmlinuz-`uname -r` ]
				then KERNEL=/boot/vmlinuz-`uname -r`
			fi
		elif [ "`basename $KERNEL`" = "$KERNEL" ]
			then
			KERNEL=/boot/$KERNEL
		fi

		if [ ! -r $KERNEL ]
			then
			echo "ERROR: Could not find kernel $KERNEL."
			echo "Please set the KERNEL variable, eg. KERNEL=/boot/vmlinuz-2.6.17.8"
			exit 1
		fi
		if kexec -l $KERNEL --append="root=$ROOTDEV $KOPTS"
		then
			echo " ready with kernel"
			echo "$KERNEL root=$ROOTDEV $KOPTS"
		else
			echo "Kexec failed."
			exit 1;
		fi
		;;
	stop)
		echo -n "Kexec: unloading"
		if kexec -u
			then
			echo "."
		else
			echo " Failed."
		fi
		;;
	*)
		echo "Usage: $0 {start|stop} [b]"
		echo "   start loads kernel set by the KERNEL variable, or current kernel if unset."
		echo "   stop unloads any loaded kernel."
		echo "   'b' as a second parameter means you wish to use bootchartd"
		exit 1
esac

exit 0

