#!/bin/sh
#
#  diskdumpctl.sh
#
#  Copyright (C) 2004, 2005  FUJITSU LIMITED
#
# $Id: diskdumpctl.sh,v 1.1 2005/02/28 21:30:23 akira Exp $

KERNEL=`uname -r | awk '{print substr($0,1,3);}'`

if [ "$KERNEL" = "2.4" ]; then
	DISKDUMPCTL_PROC="/usr/sbin/diskdumpctl_proc"
	exec $DISKDUMPCTL_PROC "$@"
	echo "$PROGRAM_NAME: exec $DISKDUMPCTL_PROC failed!" >&2
	exit 1
fi

# VERSION is given when "make install" is executed.
VERSION="1.0.1"
PROGRAM_NAME="diskdumpctl"

usage()
{
	echo "Usage: $PROGRAM_NAME [-u] device" >&2
	echo "       $PROGRAM_NAME -V" >&2
	echo >&2
	echo "Available options:" >&2
	echo "	-u:   unregister the device" >&2
	echo "	-V:   show $PROGRAM_NAME version and exit" >&2

	exit 1
}

version()
{
	echo "$PROGRAM_NAME version $VERSION" >&2
	exit 0
}

invalid_option()
{
	opt=$1
	opt=`echo $opt | tr '-' '\0'`

	echo "$PROGRAM_NAME: invalid option -- $opt" >&2
}

# Check argument
if [ $# -le 0 -o $# -ge 3 ] ; then
	usage
fi

# Check option
if [ $# = 2 ] ; then
	case "$1" in
		"-u")	DEVFILE=$2
			CMD="delete" ;;
		"-"*)	invalid_option $1
			usage ;;
		*) 	usage ;;
	esac
elif [ $# = 1 ] ; then
	case "$1" in
		"-V")	version ;;
		"-"*)	invalid_option $1
			usage ;;
		*)	DEVFILE=$1
			CMD="add" ;;
	esac
else
	usage
fi

if [ ! -e $DEVFILE ] ; then
	echo "$PROGRAM_NAME: $DEVFILE does not exist!" >&2
	exit 1
fi

if [ -L $DEVFILE ] ; then
	DEVFILE=`readlink $DEVFILE`
fi

if [ ! -b $DEVFILE ] ; then
	echo "$PROGRAM_NAME: $DEVFILE is not block device!" >&2
	exit 1
fi

# Get partition number
MINOR=`echo $DEVFILE | sed 's/^[^0-9]*//'`
if [ "$MINOR" = "" ] ; then
	MINOR=0
fi

# Get sysfs mounted point
SYSFSROOT=`grep sysfs /etc/mtab | cut -d\  -f 2`
if [ ! -d $SYSFSROOT ] ; then
	echo "$PROGRAM_NAME: sysfs is not mounted!" >&2
	exit 1
fi

DEV=`basename $(echo $DEVFILE | sed 's/[0-9]*$//')`
case $DEV in
	sd*)
		DUMPFILE=$SYSFSROOT/block/$DEV/device/dump
		if [ ! -f $DUMPFILE ] ; then
			echo "$PROGRAM_NAME: $DUMPFILE does not exist!" >&2
			exit 1
		fi

		if [ "$CMD" = "add" ] ; then
			echo $MINOR > $DUMPFILE
		else
			echo -$MINOR > $DUMPFILE
		fi
		;;
	*)
	echo "$PROGRAM_NAME: $DEVFILE is not supported!" >&2
	exit 1
	;;
esac

