#!/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 export an image to qcow2 file

# ------------ Set up the environment to source common tools ------------

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 rm 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/IMAGE/SOURCE \
    /DS_DRIVER_ACTION_DATA/IMAGE/SIZE \
    /DS_DRIVER_ACTION_DATA/IMAGE/TEMPLATE/MD5 \
    /DS_DRIVER_ACTION_DATA/IMAGE/TEMPLATE/SHA1 \
    /DS_DRIVER_ACTION_DATA/IMAGE/TEMPLATE/FORMAT \
    /DS_DRIVER_ACTION_DATA/DATASTORE/TEMPLATE/BRIDGE_LIST \
    /DS_DRIVER_ACTION_DATA/DATASTORE/TEMPLATE/VITASTOR_CONF)

unset i

SRC="${XPATH_ELEMENTS[i++]}"
SIZE="${XPATH_ELEMENTS[i++]}"
MD5="${XPATH_ELEMENTS[i++]}"
SHA1="${XPATH_ELEMENTS[i++]}"
FORMAT="${XPATH_ELEMENTS[i++]:-raw}"
BRIDGE_LIST="${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

IMPORT_SOURCE="vitastor://$DST_HOST/$SRC"
IS_JOIN="?"

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

# FIXME: this is inefficient - it pipes the image twice...

INFO_SCRIPT=$(cat <<EOF
if [ -z "$MD5" ]; then
    CHECKSUM=\$(
        $CLI dd iimg=${SRC} | ${MD5SUM} | cut -f1 -d' '
        ps=\$PIPESTATUS

        if [ "\$ps" != "0" ]; then
            exit \$ps
        fi
    )

    status=\$?

    [ "\$status" != "0" ] && exit \$status
else
    CHECKSUM="$MD5"
fi

if [ -z "\$CHECKSUM" ]; then
    exit 1
fi

cat <<EOT
<MD5><![CDATA[\$CHECKSUM]]></MD5>
<SIZE><![CDATA[$SIZE]]></SIZE>
<FORMAT><![CDATA[${FORMAT}]]></FORMAT>
EOT
EOF
)

INFO=$(ssh_monitor_and_log "$DST_HOST" "$INFO_SCRIPT" "Image info script" 2>&1)
INFO_STATUS=$?

if [ "$INFO_STATUS" != "0" ]; then
    echo "$INFO"
    exit $INFO_STATUS
fi

cat <<EOF
<IMPORT_INFO>
    <IMPORT_SOURCE><![CDATA[$IMPORT_SOURCE]]></IMPORT_SOURCE>
    $INFO
    <DISPOSE>NO</DISPOSE>
</IMPORT_INFO>"
EOF
