#!/bin/bash

#rbt

# mvds host:remote_system_ds/disk.i fe:SOURCE
#   - fe is the front-end hostname
#   - SOURCE is the path of the disk image in the form DS_BASE_PATH/disk
#   - host is the target host to deploy the VM
#   - remote_system_ds is the path for the system datastore in the host

SRC=$1
DST=$2
VM_ID=$3
DS_ID=$4

if [ -z "${ONE_LOCATION}" ]; then
    TMCOMMON=/var/lib/one/remotes/tm/tm_common.sh
else
    TMCOMMON=$ONE_LOCATION/var/remotes/tm/tm_common.sh
fi

source $TMCOMMON

DRIVER_PATH=$(dirname $0)

#-------------------------------------------------------------------------------
# Set dst path and dir
#-------------------------------------------------------------------------------
SRC_PATH=`arg_path $SRC`
SRC_HOST=`arg_host $SRC`

DST_PATH=`arg_path $DST`

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

LCM_STATE=$(onevm show -x $VM_ID | xmlstarlet sel -t -v '/VM/LCM_STATE')
SRC_DIR=$(dirname $SRC_PATH)
SEARCH_SNAP_XML=$(cat <<EOF
SNAP_PATH=("${SRC_DIR}/snap-"*.xml)
for path in "\${SNAP_PATH[@]}"; do
    if [ -e "\$path" ] && [[ "$LCM_STATE" =~ ^(34)$ ]]; 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 disk_xml in "\${XML_PATH[@]}"; do
            SRC_PATH=\$(readlink $SRC_PATH) || SRC_PATH=$SRC_PATH
            if [ "\$disk_xml" == "\$SRC_PATH" ]; then
                exit 1
            fi
        done
    fi
done
EOF
)
ssh_exec_and_log $SRC_HOST "$SEARCH_SNAP_XML" "Error remove disks, because $SRC_PATH exists in snap.xml"

DUMP_CMD=$(cat <<EOF
        set -e -o pipefail
        rm $SRC_PATH
        $SUDO $LVCHANGE -an $DST_PATH > /dev/null 2>&1
EOF
)

log "Dumping $SRC to $DST"

ssh_exec_and_log "$SRC_HOST" "$DUMP_CMD" \
    "Error dumping $SRC to $DST"

exit 0
