#!/usr/bin/ruby

# -------------------------------------------------------------------------- #
# Copyright 2002-2025, OpenNebula Project, OpenNebula Systems                #
#                                                                            #
# Licensed under the Apache License, Version 2.0 (the "License"); you may    #
# not use this file except in compliance with the License. You may obtain    #
# a copy of the License at                                                   #
#                                                                            #
# http://www.apache.org/licenses/LICENSE-2.0                                 #
#                                                                            #
# Unless required by applicable law or agreed to in writing, software        #
# distributed under the License is distributed on an "AS IS" BASIS,          #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   #
# See the License for the specific language governing permissions and        #
# limitations under the License.                                             #
#--------------------------------------------------------------------------- #

# %%RUBYGEMS_SETUP_BEGIN%%
require 'load_opennebula_paths'
# %%RUBYGEMS_SETUP_END%%

###############################################################################
# This script clones the image from the image datastore to a VM disk.
# Only for non-persistent images (equivalent for persistent images: `ln`).
###############################################################################
#
# ARGUMENTS: frontend:SOURCE host:remote_system_ds/disk.i vm_id img_ds_id
# STDIN: -
# RETURNS: -
#
###############################################################################

require_relative '../lib/tm_action'
require_relative '../../datastore/lvm'

arg_src = ARGV[0]
arg_dst = ARGV[1]
arg_vmid = ARGV[2]
_arg_imgds_id = ARGV[3]

# SRC IS AN LVFNAME
src = TransferManager::Action::Location.new(arg_src)
dst = TransferManager::Action::Location.new(arg_dst)

OpenNebula::DriverLogger.log_info "Cloning #{src.path} to #{dst.path}"

lvmdisk = MAD::LVMVM.get_from_id(arg_vmid).disk(dst.disk_id)
img_lvname = MAD::LVMImage.lvname(lvmdisk.imageid)
lvmdisk.clone_from_lv(img_lvname)
