#!/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 remove a VM image from the image repository

# ------------ 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 j 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/DATASTORE/TEMPLATE/BRIDGE_LIST \
    /DS_DRIVER_ACTION_DATA/DATASTORE/TEMPLATE/VITASTOR_CONF)

IMAGE_NAME="${XPATH_ELEMENTS[j++]}"
BRIDGE_LIST="${XPATH_ELEMENTS[j++]}"
VITASTOR_CONF="${XPATH_ELEMENTS[j++]}"

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

# -------- Remove Image from Datastore ------------

log "Removing $IMAGE_NAME from the image repository in $DST_HOST"

DELETE_CMD=$(cat <<EOF
    $CLI rm $IMAGE_NAME
EOF
)

ssh_exec_and_log "$DST_HOST" "$DELETE_CMD" "Error deleting $IMAGE_NAME in $DST_HOST"
