cat <<E_O_F >> $ROOT/etc/uniontab
/etc
/home
/root
/var/mail
E_O_F

$in_chroot /bin/mkdir -p /etc/dev.d/block


cat <<E_O_F >> $ROOT/etc/dev.d/block/usbdrive.dev
#!/bin/sh -x
#
# USB drive hotplug agent for 2.6 kernels
#
#	ACTION=add
#	DEVPATH=/block/*
#

cd /etc/hotplug
. ./hotplug.functions

SourceIfNotEmpty /etc/sysconfig/hotplug

if [ "\$HOTPLUG" == "no" -o "\$USBPLUG" == "no" ];then
    exit 0
fi

STATEPATH=/var/lib/hotplug

UNIONTAB=/etc/uniontab
UNIONCTL=/usr/sbin/unionctl
MOUNT=/bin/mount
USBROOT=/media/storage_usbroot

[ -x \$UNIONCTL -a -x \$MOUNT ] || exit 1

function restart_services() {
    mesg "Restarting services with \"usbroot\" settings..."
    [ -s \$USBROOT/etc/sysconfig/clock ] && /sbin/service clock start
    [ -d \$USBROOT/etc/net ] && /sbin/service network restart
}

function add_unionfs_branches_to_usbroot() {
    mesg "Adding unionfs branches to \$USBROOT"
    grep -ve '^\(#\|\$\)' \$UNIONTAB |while read mntpt; do
        if [ -d \$mntpt ]; then
	    mkdir -p \$USBROOT/\$mntpt
	    mesg "Adding unionfs rw branch for \$mntpt to \$USBROOT/\$mntpt ..."
	    \$UNIONCTL \$mntpt --add --mode rw \$USBROOT/\$mntpt && \
	    mesg "Successfully added unionfs branch for \$mntpt" || \
	    mesg "Adding unionfs branch for \$mntpt failed."
	fi
	[ \$mntpt == /etc ] && restart_services
    done
}

function mount_usbroot() {
    /bin/mkdir \$USBROOT
    mesg "Trying to mount /dev/\$NAME to \$USBROOT ..."
    \$MOUNT /dev/\$NAME \$USBROOT -o sync && mesg "Successfully mounted." || exit 1
    mesg "Removing \$USBROOT/etc/mtab"
    rm -f \$USBROOT/etc/mtab
    if [ -s \$UNIONTAB ]; then
	add_unionfs_branches_to_usbroot
    fi
}

case \$ACTION in

add)
# FIXME: how to detect LABEL from udev (or HAL) ?
    NAME=\`udevinfo -q name -p \$DEVPATH\`
# FIXME: remove trailing space from blkid output ?
    LABEL=\`blkid /dev/\$NAME -s LABEL | cut -d '=' -f2\`
    [ \$LABEL == \"usbroot\" ] || exit 0
    mesg "Found label \$LABEL on \$DEVPATH"
    mount_usbroot
    exit 0
    ;;
remove)
# FIXME: udevinfo not works without device
    NAME=\`udevinfo -q name -p \$DEVPATH\`
    umount /dev/\$NAME
    exit 0
    ;;
*)
    debug_mesg USB drive \$ACTION event not supported
    exit 1
    ;;

esac

E_O_F

$in_chroot /bin/chmod 755 /etc/dev.d/block/usbdrive.dev
