#!/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 directly activates the image from the image datastore as a VM disk.
# Only for persistent images (equivalent for non-persistent images: `clone`).
###############################################################################
#
# ARGUMENTS: frontend:SOURCE host:remote_system_ds/disk.i vm_id img_ds_id
# STDIN: -
# RETURNS: -
#
###############################################################################

require 'base64'

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

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

action = TransferManager::Action.new(:vm_id => arg_vmid, :action_name => 'ln')

src = TransferManager::Action::Location.new(arg_src)
dst = TransferManager::Action::Location.new(arg_dst)

img_id = src.path.basename.to_s.split('-')[-1].to_i

oneimage = OpenNebula::Image.new_with_id(img_id, action.one)
rc = oneimage.info
raise rc.message.to_s if OpenNebula.is_error?(rc)

oneimgds = OpenNebula::Datastore.new_with_id(arg_imgds_id, action.one)
rc = oneimgds.info
raise rc.message.to_s if OpenNebula.is_error?(rc)

lvmimgds = MAD::LVMDatastore.new(oneimgds.to_xml)
lvmimg = MAD::LVMImage.new(oneimage.to_xml, lvmimgds)

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

lvmimg.activate_and_link(dst)
