#!/bin/bash

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

# clone fe:SOURCE host:remote_system_ds/disk.i size
#   - fe is the front-end hostname
#   - SOURCE is the path of the disk image in the form DS_BASE_PATH/disk
#   - host is the target host to deploy the VM
#   - remote_system_ds is the path for the system datastore in the host

SRC=$1
DST=$2
VM_ID=$3
DS_ID=$4

#--------------------------------------------------------------------------------

if [ -z "${ONE_LOCATION}" ]; then
    TMCOMMON=/var/lib/one/remotes/tm/tm_common.sh
    LIB_LOCATION=/usr/lib/one
else
    TMCOMMON=$ONE_LOCATION/var/remotes/tm/tm_common.sh
    LIB_LOCATION=$ONE_LOCATION/lib
fi

DRIVER_PATH=$(dirname $0)

source $TMCOMMON

#-------------------------------------------------------------------------------
# Compute the destination image name
#-------------------------------------------------------------------------------

DST_HOST=`arg_host $DST`

SRC_PATH=`arg_path $SRC`
DST_PATH=`arg_path $DST`

DST_DIR=`dirname $DST_PATH`

DISK_ID=$(echo $DST|awk -F. '{print $NF}')
VM_DST="${SRC_PATH}-${VM_ID}-${DISK_ID}"
DST_DS_ID=`echo $DST | sed s#//*#/#g | awk -F/ '{print $(NF-2)}'`

#-------------------------------------------------------------------------------
# Get Image information
#-------------------------------------------------------------------------------

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

unset i j XPATH_ELEMENTS

while IFS= read -r -d '' element; do
    XPATH_ELEMENTS[i++]="$element"
done < <(onevm show -x $VM_ID | $XPATH  \
    /VM/TEMPLATE/DISK[DISK_ID=$DISK_ID]/VITASTOR_CONF \
    /VM/TEMPLATE/DISK[DISK_ID=$DISK_ID]/SIZE)

VITASTOR_CONF="${XPATH_ELEMENTS[j++]}"
SIZE="${XPATH_ELEMENTS[j++]}"

#-------------------------------------------------------------------------------
# Get Datastore information
#-------------------------------------------------------------------------------

unset i j XPATH_ELEMENTS

while IFS= read -r -d '' element; do
    XPATH_ELEMENTS[i++]="$element"
done < <(onedatastore show -x $DST_DS_ID | $XPATH \
    /DATASTORE/TEMPLATE/POOL_NAME)

POOL_NAME="${XPATH_ELEMENTS[j++]}"

disable_local_monitoring $DST_HOST $DST_DIR

#-------------------------------------------------------------------------------
# Clone the image
#-------------------------------------------------------------------------------

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

CLONE_CMD=$(cat <<EOF
    $CLI create --parent $SRC_PATH --size ${SIZE}M $VM_DST
EOF
)

ssh_exec_and_log "$DST_HOST" "$CLONE_CMD" "Error cloning $SRC_PATH to $VM_DST in $DST_HOST"
exit 0
