#!/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

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

set -e
ssh "$SRC_HOST" 'rm -f "$FILE"'
ssh "$SRC_HOST" "'${SCRIPTS_REMOTE_DIR:-/var/tmp/one}/vmm/kvm/save' $@"
set +e

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

unset i j XPATH_ELEMENTS

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 \
    /VMM_DRIVER_ACTION_DATA/DATASTORE/TEMPLATE/POOL_NAME)

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

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

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

ssh_exec_and_log "$SRC_HOST" "$CLI dd if=$FILE oimg=$DST_IMAGE conv=trunc" "Error importing checkpoint into $DST_IMAGE"
ssh_exec_and_log "$SRC_HOST" "$RM -f $FILE" "Error removing checkpoint ($FILE)"

exit 0
