#!/bin/bash

#rbt

# DELETE <host:remote_system_ds/disk.i|host:remote_system_ds/>
#   - host is the target host to deploy the VM
#   - remote_system_ds is the path for the system datastore in the host


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

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

#-------------------------------------------------------------------------------
# Return if deleting a disk, we will delete them when removing the
# remote_system_ds directory for the VM (remotely)
#-------------------------------------------------------------------------------
DST_PATH=`arg_path $DST`
DST_HOST=`arg_host $DST`

#DS_SYS_ID=$(echo $DST_PATH | grep -E '\/disk\.[[:digit:]]+$' | $AWK -F '/' '{print $(NF-2)}')
#DS_SYS_ID=$(echo $DST_PATH | $AWK -F '/' '{print $(NF-1)}')
DISK_ID=$(basename ${DST_PATH} | cut -d. -f2)

DS_SYS_ID=${DS_SYS_ID:-"$DS_ID"}
VG_NAME="vg-one-$DS_SYS_ID"

LCM_STATE=$(onevm show -x $VM_ID | xmlstarlet sel -t -v '/VM/LCM_STATE')
DST_DIR=$(dirname $DST_PATH)
SEARCH_SNAP_XML=$(cat <<EOF
SNAP_PATH=("${DST_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
            DST_PATH=\$(readlink $DST_PATH) || DST_PATH=$DST_PATH
            if [ "\$disk_xml" == "\$DST_PATH" ]; then
                exit 1
            fi
        done
    fi
done
EOF
)
ssh_exec_and_log $DST_HOST "$SEARCH_SNAP_XML" "Error remove disks, because $DST_PATH exists in snap.xml"

DELETE_CMD=$(cat <<EOF
    set -x
    DEV=\$(readlink $DST_PATH)

    if [ -d "$DST_PATH" ]; then
        for disk in $(sudo find /var/lib/one/datastores/$DS_SYS_ID/$VM_ID/  -name "*disk.*"); do
            volume=$(readlink \$disk)
            if echo "\$volume" | grep "^/dev/$VG_NAME" &>/dev/null; then
                $SUDO $LVREMOVE -f \$volume
            fi
        done
        rm -rf "$DST_PATH"
    else
        if [ -e "${DST_PATH}" ]; then
            rm -rf ${DST_PATH}
        fi

        DS_SYS_ID=$(echo $DST_PATH | grep -E '\/disk\.[[:digit:]]+$' | $AWK -F '/' '{print $(NF-2)}')
        DS_VG_NAME="vg-one-\$DS_SYS_ID"

        if echo "\$DEV" | grep "^/dev/\$DS_VG_NAME" &>/dev/null; then
            $SUDO $LVREMOVE -f \$DEV
        fi
    fi
EOF
)

ssh_exec_and_log "$DST_HOST" "$DELETE_CMD" \
        "Error deleting $DST_PATH"
