#!/bin/bash

# -------------------------------------------------------------------------- #
# Copyright 2002-2021, OpenNebula Project, OpenNebula Systems                #
#                                                                            #
# Licensed under the Apache License, Version 2.0 (the "License"); you may    #
# not use this file except in compliance with the License. You may obtain    #
# a copy of the License at                                                   #
#                                                                            #
# http://www.apache.org/licenses/LICENSE-2.0                                 #
#                                                                            #
# Unless required by applicable law or agreed to in writing, software        #
# distributed under the License is distributed on an "AS IS" BASIS,          #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   #
# See the License for the specific language governing permissions and        #
# limitations under the License.                                             #
#--------------------------------------------------------------------------- #

source $(dirname $0)/../../etc/vmm/kvm/kvmrc
source $(dirname $0)/../../scripts_common.sh

DOMAIN="$1"
SOURCE="$2"
TARGET="$3"
TARGET_INDEX="$4"
VMID="$5"
DST_HOST="$6"
DST_DIR=`dirname $SOURCE`
DRIVER_PATH=$(dirname $0)

XPATH="${DRIVER_PATH}/../../datastore/xpath.rb --stdin"

STDIN=$(cat -)
echo "$STDIN" | tr -d '\n' | grep -q '^ *<.*> *$' || STDIN="$(echo "$STDIN" | base64 -d)"

unset i j XPATH_ELEMENTS
while IFS= read -r -d '' element; do
    XPATH_ELEMENTS[i++]="$element"
done < <(echo $STDIN | $XPATH \
                    /VMM_DRIVER_ACTION_DATA/VM/LCM_STATE \
                    /VMM_DRIVER_ACTION_DATA/DATASTORE/TEMPLATE/TM_MAD )

LCM_STATE="${XPATH_ELEMENTS[j++]}"
TM_MAD="${XPATH_ELEMENTS[j++]}"

if [ "$TM_MAD" == "shared" ] || [ "$TM_MAD" == "qcow2" ] || [ "$TM_MAD" == "brest_lvm" ]; then
    SEARCH_SNAP_XML=$(cat <<EOF
SNAP_PATH=("${DST_DIR}/snap-"*.xml)
for path in "\${SNAP_PATH[@]}"; do
    if [ -e "\$path" ] && [[ "$LCM_STATE" =~ ^(17)$ ]]; then
        if [ "$TM_MAD" == "brest_lvm" ]; then
            XML_PATH=(\$(xmllint --xpath '/domainsnapshot/domain/devices/disk/source/@file | /domainsnapshot/domain/devices/disk/source/@dev' "\$path" | xargs | sed 's/file=//g; s/dev=//g'))
            for lint_xml in "\${XML_PATH[@]}"; do
                SOURCE=\$(readlink $SOURCE) || SOURCE=$SOURCE
                if [ "\$lint_xml" == "\$SOURCE" ]; then
                    exit 1
                fi
            done
        else
            XML_PATH=(\$(xmllint --xpath '/domainsnapshot/domain/devices/disk/source/@file' "\$path" | xargs | sed 's/file=//g'))
            for lint_xml in "\${XML_PATH[@]}"; do
                if [ "\$lint_xml" == "$SOURCE" ]; then
                    exit 1
                fi
            done
        fi
    fi
done
EOF
)
    ssh_exec_and_log $DST_HOST "$SEARCH_SNAP_XML" "Error remove disks, because $SOURCE exists in snap.xml"
fi

DETACH_PARAMS="--domain $DOMAIN --target $TARGET"

exec_and_log "virsh --connect $LIBVIRT_URI detach-disk $DETACH_PARAMS" \
    "Could not detach $TARGET from $DOMAIN"

virsh --connect $LIBVIRT_URI dumpxml $DOMAIN | \
    xmllint -xpath "//disk/target[@dev='$TARGET']" - >/dev/null 2>&1

if [ $? -eq 0 ] ; then
    error_message "Could not detach $TARGET from $DOMAIN"
    exit -1
fi

exit 0
