#! /bin/bash
#
# attach-static-vdis    Attaches any statically-configured VDIs to dom0

STATE_DIR=/etc/xensource/static-vdis

[ -d ${STATE_DIR} ] || exit 0
[ -e /opt/xensource/bin/static-vdis ] || exit 0

clear_stale_state(){
	for i in "${STATE_DIR}"/*; do
	    # Clear the now-stale symlink to the attached disk. From this point the disk will
	    # be considered 'currently-attached=false'
	    rm -f "${i}"/disk

	    # If the disk was supposed to be deleted altogether on reboot then do it now
	    UUID=$(cat "${i}"/vdi-uuid)
	    if [ -e "${i}"/delete-next-boot ]; then
	       logger "Deleting stale static-configured state for VDI: ${UUID}"
	       rm -rf "${i}"
	    fi;
	done
}

attach_all(){
	RC=0

	for i in "${STATE_DIR}"/*; do
	    UUID=$(cat "${i}"/vdi-uuid)
	    logger "Attempting to attach VDI: ${UUID}"
	    if ! OUTPUT=$(/opt/xensource/bin/static-vdis attach "${UUID}" 2>&1); then
	       RC=1
	       logger "Attempt to attach VDI: ${UUID} failed -- skipping (Error was: ${OUTPUT})"
	       return $RC
	    fi
	done
	return $RC
}

detach_all(){
	for i in "${STATE_DIR}"/*; do
	    UUID=$(cat "${i}"/vdi-uuid)
	    logger "Attempting to detach VDI: ${UUID}"
	    if ! OUTPUT=$(/opt/xensource/bin/static-vdis detach "${UUID}" 2>&1); then
	       logger "Attempt to detach VDI: ${UUID} failed -- skipping (Error was: ${OUTPUT})"
	    fi
	done
}

start() {
	echo -n $"Attempting to attach all statically-configured VDIs"
	clear_stale_state
	attach_all
	RC=$?
	echo 
	return $RC
}


stop() {
	echo -n $"Attempting to detach all statically-configured VDIs"
	detach_all
	echo
	return 0
}

case "$1" in
start)
	start
	;;
stop)
	stop
	;;
restart)
	start
	;;
*)
	echo $"Usage: $0 {start|stop|restart}"
	exit 1
esac
