#!/usr/bin/env bash

# It's probably more safe to use VM/VDI variables to destroy VM instead of
# reading in "$crundir/xcp_vm_uuid" and "$crundir/xcp_vdi_uuid" if files are
# removed by an external process.
workpath="$1"
vm_uuid="$2"
vdi_uuid="$3"
wrapper_pid="$4"
container_pipe="$5"

trap '' INT TERM ABRT

domid=''
read line <$container_pipe
if [[ "$line" == 'start' ]]; then
    domid=`list_domains | grep -i "$vm_uuid" | awk '{print $1}'`
else
    kill -9 $wrapper_pid
fi

if [[ $domid ]]; then
    path=/local/domain/$domid
    xenstore-watch $path > $container_pipe &
    watch_pid=$!
    while read watch ; do
        xenstore-read $path &>/dev/null
        if [ $? -ne 0 ]; then
            kill $wrapper_pid
            break
        fi
    done <$container_pipe
    kill -9 $watch_pid
fi

tail --pid="$wrapper_pid" -f /dev/null
"$workpath/delete" "$vm_uuid" "$vdi_uuid"
wait
