#!/bin/bash

hd_arr[10]=a
hd_arr[11]=b
hd_arr[12]=c
hd_arr[13]=d
hd_arr[14]=e
hd_arr[15]=f

hexdigit()
{
	if [ $1 -lt 10 ] ; then 
		RET=$1
	else 
		RET=${hd_arr[$1]}
	fi
}

hexnumber()
{
	hexdigit $(($1/16))
	ret2=$RET
	hexdigit $(($1%16))
	HEXNUMBER="$ret2"$RET
}


process()
{
	if ! [ "x""$1" = "xfile" ] ; then
		exec /etc/xen/scripts/block "$@"	
	fi
	while true ; do
		dev=$(losetup -f --show $2)
		if [ -n "$dev" ] ; then break ; fi
	done
	hexnumber ${dev:9:70}
	xenstore-write "$XENBUS_PATH/node" "$dev" \
		"$XENBUS_PATH/physical-device" "7:"$HEXNUMBER \
 		"$XENBUS_PATH/hotplug-status" connected
}

#exec 2>>/tmp/block.$$
#set -x
export PATH="/sbin:/bin:/usr/bin:/usr/sbin:$PATH"

XENBUS_PATH="${XENBUS_PATH:?}"
if ! [ "$1" = "add" ] || ! [ -f /var/run/qubes/fast_block_attach ] ; then
	exec /etc/xen/scripts/block "$@"
fi
  
vars=$(xenstore-read "$XENBUS_PATH/type" "$XENBUS_PATH/params")
process $vars
exit 0
