#!/bin/bash

#rbt

# POSTMIGRATE SOURCE DST remote_system_dir vmid dsid template
#  - SOURCE is the host where the VM is running
#  - DST is the host where the VM is to be migrated
#  - remote_system_dir is the path for the VM home in the system datastore
#  - vmid is the id of the VM
#  - dsid is the target datastore
#  - template is the template of the VM in XML and base64 encoded

SRC_HOST=$1
DST_HOST=$2

DST_PATH=$3

VMID=$4
DSID=$5

TEMPLATE_64=$6

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

. $TMCOMMON

#if migrate between datastores
if [ "$SRC_HOST" == "$DST_HOST" ]; then
    CLEAN_CMD=$(cat <<EOF
        set -e -o pipefail
        while read disk; do
            tdisk=(\$disk)
            volume=\${tdisk[3]}
            if echo "\$volume" | grep "lv-one-vm" &>/dev/null; then
                $SUDO $LVREMOVE --yes \$volume
            else
                rm -rf \$disk
            fi
        done < $DST_PATH/before_ds

        rm -f $DST_PATH/before_ds
EOF
)

    ssh_exec_and_log "$DST_HOST" "$CLEAN_CMD" "Error clean old logic volumes"  
    exit 0
fi

CMD=$(cat <<EOF
    set -ex -o pipefail
    rm -rf $DST_PATH #rbt
EOF
)

ssh_exec_and_log $SRC_HOST "$CMD" \
    "Error running brest_lvm postmigrate on $SRC_HOST"

migrate_other "$@"
