#!/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%%

###############################################################################
#
# ARGUMENTS: SOURCE DST remote_system_dir vmid dsid
#  - SOURCE is the host where the VM is running
#  - DST is the host where the VM is to be migrated
#  - remote_system_dir is the path for the VM home in the system datastore
#  - vmid is the id of the VM
#  - dsid is the target datastore
# STDIN: Base64-encoded VM template. Format:
#     <VM>
#         ...
#     </VM>
# RETURNS: -
#
###############################################################################

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

arg_srchost = ARGV[0]
arg_dsthost = ARGV[1]
arg_sysdir = ARGV[2]
_arg_vmid = ARGV[3]
_arg_sysds_id = ARGV[4]

daction64 = STDIN.read
daction = Base64.decode64 daction64
delm = REXML::Document.new(daction).root

if arg_srchost == arg_dsthost
    OpenNebula::DriverLogger.log_info "Not moving between the same host (#{arg_srchost})"
    exit 0
end

# Build script to activate all LVM disks DST host
lvmvm = MAD::LVMVM.new(delm)
MAD::LVMWrapper.with_lvm_lock(lvmvm.pool.vgname) do
    MAD.run(arg_dsthost, MAD::LVMWrapper.lvmsync(lvmvm.activate_disks_sh),
            "Error activating LVM disks in #{arg_dsthost}")
end

# Copy VM dir from SRC to DST host
MAD.run(arg_srchost, <<~EOF, "Error migrating VM dir from #{arg_srchost} to #{arg_dsthost}")
    tar -C '#{arg_sysdir}' -cSf - . | ssh "#{arg_dsthost}" "tar -xSf - -C '#{arg_sysdir}'"
EOF

action = TransferManager::Action.new(:vm_id => lvmvm.id, :action_name => 'premigrate')
action.migrate_other(daction64)
