#!/bin/bash

# Vitastor OpenNebula driver
# Copyright (c) Vitaliy Filippov, 2024+
# License: Apache-2.0 http://www.apache.org/licenses/LICENSE-2.0

DRIVER_PATH=$(dirname $0)

source $DRIVER_PATH/../../etc/vmm/kvm/kvmrc
source $DRIVER_PATH/../../scripts_common.sh

FILE=$1
DST_HOST=$2
DEPLOY_ID=$3
VM_ID=$4
DS_ID=$5

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

while IFS= read -r -d '' element; do
    XPATH_ELEMENTS[i++]="$element"
done < <(cat | $XPATH \
    /VMM_DRIVER_ACTION_DATA/DATASTORE/TEMPLATE/VITASTOR_CONF \
    /VMM_DRIVER_ACTION_DATA/DATASTORE/TEMPLATE/IMAGE_PREFIX)

VITASTOR_CONF="${XPATH_ELEMENTS[j++]}"
IMAGE_PREFIX="${XPATH_ELEMENTS[j++]:-one}"

CLI=vitastor-cli
if [ -n "$VITASTOR_CONF" ]; then
    CLI="$CLI --config_path $VITASTOR_CONF"
fi

SRC_IMAGE="${IMAGE_PREFIX}-sys-${VM_ID}-checkpoint"

ssh_exec_and_log "$DST_HOST" "$CLI dd iimg=$SRC_IMAGE of=$FILE" "Error exporting checkpoint into from $SRC_IMAGE to $FILE"
ssh_exec_and_log "$DST_HOST" "$CLI rm $SRC_IMAGE" "Error removing checkpoint $SRC_IMAGE"

set -e
ssh "$DST_HOST" "'${SCRIPTS_REMOTE_DIR:-/var/tmp/one}/vmm/kvm/restore' $@"
