#!/bin/bash

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

# This script is used to copy a VM image (SRC) to the image repository as DST

# -------- Set up the environment to source common tools & conf ------------
if [ -z "${ONE_LOCATION}" ]; then
    LIB_LOCATION=/usr/lib/one
else
    LIB_LOCATION=$ONE_LOCATION/lib
fi

. $LIB_LOCATION/sh/scripts_common.sh

DRIVER_PATH=$(dirname $0)
source ${DRIVER_PATH}/../libfs.sh

# -------- Get cp and datastore arguments from OpenNebula core ------------

DRV_ACTION=`cat -`
ID=$1

XPATH="${DRIVER_PATH}/../xpath.rb -b $DRV_ACTION"

unset i XPATH_ELEMENTS

while IFS= read -r -d '' element; do
    XPATH_ELEMENTS[i++]="$element"
done < <($XPATH \
    /DS_DRIVER_ACTION_DATA/DATASTORE/BASE_PATH \
    /DS_DRIVER_ACTION_DATA/DATASTORE/TEMPLATE/BRIDGE_LIST \
    /DS_DRIVER_ACTION_DATA/DATASTORE/TEMPLATE/POOL_NAME \
    /DS_DRIVER_ACTION_DATA/DATASTORE/TEMPLATE/IMAGE_PREFIX \
    /DS_DRIVER_ACTION_DATA/IMAGE/PATH \
    /DS_DRIVER_ACTION_DATA/IMAGE/SIZE \
    /DS_DRIVER_ACTION_DATA/DATASTORE/TEMPLATE/VITASTOR_CONF)

unset i

BASE_PATH="${XPATH_ELEMENTS[i++]}"
BRIDGE_LIST="${XPATH_ELEMENTS[i++]}"
POOL_NAME="${XPATH_ELEMENTS[i++]}"
IMAGE_PREFIX="${XPATH_ELEMENTS[i++]:-one}"
SRC="${XPATH_ELEMENTS[i++]}"
SIZE="${XPATH_ELEMENTS[i++]}"
VITASTOR_CONF="${XPATH_ELEMENTS[i++]}"

DST_HOST=`get_destination_host $ID`

if [ -z "$DST_HOST" ]; then
    error_message "Datastore template missing 'BRIDGE_LIST' attribute."
    exit -1
fi

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

SAFE_DIRS=""

DST="${IMAGE_PREFIX}-${ID}"

ssh_exec_and_log "$DST_HOST" "$CLI create --parent $SRC $DST" \
    "Error during $CLI create --parent $SRC $DST in $DST_HOST"

ssh_exec_and_log "$DST_HOST" "$CLI flatten $DST" \
    "Error during $CLI create flatten $DST in $DST_HOST"

echo "$DST raw"
