#!/bin/sh

TYPE=`echo ${XENBUS_PATH} | cut -f 2 -d '/'`
DOMID=`echo ${XENBUS_PATH} | cut -f 3 -d '/'`
DEVID=`echo ${XENBUS_PATH} | cut -f 4 -d '/'`

HOTPLUG=/xapi/${DOMID}/hotplug/${TYPE}/${DEVID}
HOTPLUG_STATUS="${XENBUS_PATH}/hotplug-status"

syslog ()
{
	logger -tscripts-block "$*"
}

case "$1" in
add)
        params=$(xenstore-read "${XENBUS_PATH}/params")
        frontend="/local/domain/${DOMID}/device/${TYPE}/${DEVID}"
        type=$(xenstore-read "${frontend}/device-type")
        syslog "${XENBUS_PATH}: add type=${type} params=\"${params}\""
        # We don't have PV drivers for CDROM devices, so we prevent blkback
        # from opening the physical-device
        if [ "${type}" != "cdrom" ]; then
          physical_device=$(/usr/bin/stat --format="%t:%T" "${params}")
          syslog "${XENBUS_PATH}: physical-device=${physical_device}"
          xenstore-exists "${XENBUS_PATH}/physical-device"
          if [ $? -eq 1 ]; then
            xenstore-write "${XENBUS_PATH}/physical-device" "${physical_device}"
          fi
        fi
        xenstore-write "${HOTPLUG}/hotplug" "online"
        xenstore-write "${HOTPLUG_STATUS}" "connected"
	;;
change)
	syslog "${XENBUS_PATH}: change"
	;;
remove)
	syslog "${XENBUS_PATH}: change"
    xenstore-rm "${HOTPLUG_STATUS}"
	xenstore-rm "${HOTPLUG}/hotplug"
	;;
esac
