#!/usr/bin/env ruby
#
# frozen_string_literal: true

# ---------------------------------------------------------------------------- #
# 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.                                               #
# ---------------------------------------------------------------------------- #

# premigrate: It is executed before a livemigration operation is issued to the hypervisor. Note that
# only the premigrate script from the system datastore will be used. Any customization must be done
# for the premigrate script of the system datastore, although you will probably add operations for
# other backends than that used by the system datastore.
# Base64 encoded VM XML is sent via stdin.
# ARGUMENTS: source_host dst_host remote_system_dir vmid dsid
#   - src_host is the host the VM is in.
#   - dst_host is the target host to migrate the VM to
#   - remote_system_ds_dir is the path for the VM directory in the system datastore in the host
#   - vmid is the id of the VM
#   - dsid is the target datastore
require_relative '../lib/tm_action'

arg_srchost = ARGV[0]
arg_dsthost = ARGV[1]
arg_dstpath = ARGV[2]
arg_vmid    = ARGV[3]
_arg_dsid   = ARGV[4]
template64  = STDIN.read

premg = TransferManager::Action.new(:vm_id => arg_vmid,
                                    :action_name => 'premigrate')
dst   = TransferManager::Action::Location.new([arg_dsthost, arg_dstpath])

#--------------------------------------------------------------------------------

if arg_srchost == dst.host
    OpenNebula::DriverLogger.log_info <<~EOF
        Not moving #{arg_srchost} to #{dst.host}, they are the same host
    EOF
    exit 0
end

rc = premg.ssh(:host => dst.host,
               :cmds => "rm -rf '#{dst.path}'",
               :err_msg => 'Error removing target path to prevent overwrite errors',
               :nostdout => false,
               :nostderr => false)
exit(rc.code) if rc.code != 0

premg.migrate_other(template64)
