#!/bin/bash
# $Id: 50-hwscan.dev 314 2005-01-21 16:02:02Z hare $
# set -x
#
# block hotplug policy agent for Linux kernels
#
# Kernel BLOCK hotplug params include:
#	
#	ACTION=%s [add or remove]
#	DEVPATH=%s
#
# bash required due to echo | while read line ; do : ; done
#
# Logic is like this:
# - call hwscanqueue --block for all full disks
# - call hwscanqueue --scan only for usb-storage disks
# - mount devices (either full disks or partitions) if
# HOTPLUG_USE_SUBFS is not 'no' and if an matching entry
# from /etc/fstab or /proc/mounts is found.
#

cd /etc/hotplug
. ./hotplug.functions
# DEBUG=yes export DEBUG

if [ "$DEVPATH" = "" ]; then
    mesg Bad BLOCK invocation: \$DEVPATH is not set
    exit 1
fi

#
# generic section
#
if [ -e /sbin/hwscanqueue ]; then
    HWSCAN=/sbin/hwscanqueue
elif [ -e /usr/sbin/hwscanqueue ]; then
    HWSCAN=/usr/sbin/hwscanqueue
fi
BLKID=/sbin/blkid

do_mount=
if [ "$DEVNAME" ] ; then
    real_device="$DEVNAME"
else
    real_device=/dev/${DEVPATH##*/}
fi

# check whether the devpath has a 'device' link
pname=""
if [ -e /sys$DEVPATH/device ]; then
    dname=`cd -P /sys$DEVPATH/device; echo $PWD`
else
    if [ -e /sys$DEVPATH/../device ]; then
	dname=`cd -P /sys$DEVPATH/../device; echo $PWD`
    fi
fi

# Get the type of disk
if [ -n "$dname" ]; then
    pname=${dname%/*}
    pname=/sys/class/scsi_host/${pname##*/}/proc_name
    if [ -f "$pname" ]; then
	read dtype < "$pname"
    fi
fi


#
# do the real action
#
if [ -z "$HWSCAN" ]; then
    # We only need to execute $HWSCAN
    exit 0
fi

case $ACTION in
    add)
	mesg "new block device $DEVPATH"
	case "$DEVPATH" in
	    *[0-9])
		# Register partition
		$HWSCAN --partition "$real_device"
	    ;;
	    *)
		$HWSCAN --block "$real_device"
		if [ "$dtype" = "usb-storage" ] ; then
		    $HWSCAN --scan=$real_device
		fi
		;;
	esac

	# We always call blkid as we don't know whether
	# the filesystem might span the entire disk
	if [ -x "$BLKID" -a "$real_device" != /dev/fd0 ]; then
	    $BLKID "$real_device"
	fi
	;;

    remove)
	case "$DEVPATH" in
	    *[0-9])
		# Register partition
		$HWSCAN --partition "$real_device"
	    ;;
	    *)
		# We can't figure out the real device type
		# as the device is already gone from sysfs
		$HWSCAN --stop=$real_device
		$HWSCAN --block "$real_device"
		;;
	esac
	;;
    *)
	debug_mesg BLOCK $ACTION event not supported
	exit 1 ;;
esac
