#!/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 '/'`

VM=$(xenstore-read "/local/domain/${DOMID}/vm" 2> /dev/null)
DOMUUID=$(xenstore-read "${VM}/uuid" 2> /dev/null)
PRIVATE=/xapi/${DOMUUID}/private/${TYPE}/${DEVID}
HOTPLUG=/xapi/${DOMUUID}/hotplug/${DOMID}/${TYPE}/${DEVID}
HOTPLUG_STATUS="${XENBUS_PATH}/hotplug-status"

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

case "$1" in
add)
        params=$(xenstore-read "${XENBUS_PATH}/params")
        params=$(readlink $params || echo $params)
        frontend="/local/domain/${DOMID}/device/${TYPE}/${DEVID}"
        syslog "${XENBUS_PATH}: add params=\"${params}\""
        # We don't have PV drivers for CDROM devices, so we prevent blkback
        # from opening the physical-device
        xenstore-exists "${PRIVATE}/no-physical-device"
        if [ $? -ne 0 ]; 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
			syslog "${XENBUS_PATH}: writing physical-device=${physical-device}"
            xenstore-write "${XENBUS_PATH}/physical-device" "${physical_device}"
          fi
        else
          syslog "${XENBUS_PATH}: not writing physical-device because no-physical-device is present"
        fi
        xenstore-write "${HOTPLUG}/hotplug" "online"
        xenstore-write "${HOTPLUG_STATUS}" "connected"
	;;
change)
	syslog "${XENBUS_PATH}: change"
	;;
remove)
	syslog "${XENBUS_PATH}: remove"
    xenstore-rm "${HOTPLUG_STATUS}"
	xenstore-rm "${HOTPLUG}/hotplug"
	;;
esac
