#!/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 moves an image back to its datastore (persistent images).
#
# As the disks are activated directly, it only needs to deactivate the volume
# and remove the symlink.
###############################################################################
#
# ARGUMENTS: host:remote_system_ds/disk.i SOURCE vmid img_ds_id
#   SOURCE is the path of the disk image in the form vg/lv
#   host is the target host whiere the VM is deployed
# STDIN: -
# RETURNS: -
#
###############################################################################

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

arg_dst = ARGV[0]
arg_source = ARGV[1]
arg_vmid = ARGV[2]
arg_img_ds_id = ARGV[3]

action = TransferManager::Action.new(:vm_id => arg_vmid, :action_name => 'mvds')
dst = TransferManager::Action::Location.new(arg_dst)

host =
    if action.undeployed?
        MAD::LVMDatastore.get_from_id(arg_img_ds_id).pick_bridge
    else
        dst.host
    end

lv = MAD::LV.new(*arg_source.split('/'))
MAD::LVMWrapper.with_lvm_lock(lv.vgname) do
    MAD.run(host, MAD::LVMWrapper.lvmsync(<<~EOF), "Error deactivating thin LV '#{arg_source}'")
        #{lv.activate_sh(false)}
        rm -f '#{dst.path}'
    EOF
end
