#!/bin/bash

# -------------------------------------------------------------------------- #
# Copyright 2002-2020, 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

deploy_id=$1
dest_host=$2

# migration can't be done with domain snapshots, drop them first
snaps=$(monitor_and_log \
   "virsh --connect $LIBVIRT_URI snapshot-list $deploy_id --name 2>/dev/null" \
   "Failed to get snapshots for $deploy_id")

for snap in $snaps; do
    exec_and_log \
        "virsh --connect $LIBVIRT_URI snapshot-delete $deploy_id --snapshotname $snap --metadata" \
        "Failed to delete snapshot $snap from $deploy_id"
done

# do live migration, but cleanup target host in case of error
virsh --connect $LIBVIRT_URI migrate --live $MIGRATE_OPTIONS $deploy_id $QEMU_PROTOCOL://$dest_host/system

RC=$?

if [ $RC -ne 0 ]; then
    for CLEAN_OP in destroy undefine; do
        virsh --connect $QEMU_PROTOCOL://$dest_host/system "${CLEAN_OP}" $deploy_id >/dev/null 2>&1
    done

    error_message "Could not migrate $deploy_id to $dest_host"
    exit $RC
fi

if [ "$SYNC_TIME" = "yes" ]; then
    (
        for i in $(seq 3); do
            virsh --connect $QEMU_PROTOCOL://$dest_host/system domtime --sync $deploy_id && break
            [ "$i" -gt 1 ] && sleep 6
        done
    ) &> /dev/null &
fi
