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

# delete: removes either the system datastore’s directory of the VM or a disk itself.
# ARGUMENTS: host:remote_system_ds/disk.i|host:remote_system_ds/ vm_id ds_id
#   - host is the target host to deploy the VM
#   - remote_system_ds is the path for the system datastore in the host
#   - vm_id is the id of the VM
#   - ds_id is the source datastore (the images datastore) for normal disks or target datastore (the
#     system datastore) for volatiled disks

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

arg_dst  = ARGV[0]
arg_vmid = ARGV[1]
_arg_dsid = ARGV[2]

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

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

#-------------------------------------------------------------------------------
# Return if deleting a disk, we will delete them when removing the
# remote_system_ds directory for the VM (remotely)
#-------------------------------------------------------------------------------

OpenNebula::DriverLogger.log_info "Deleting #{dst.path}"

delete_file = <<~SCRIPT
    [ -e "#{dst.path}" ] || exit 0

    times=10
    function="rm -rf #{dst.path}"

    count=1

    ret=$($function)
    error=$?

    while [ $count -lt $times -a "$error" != "0" ]; do
        sleep 1
        count=$(( $count + 1 ))
        ret=$($function)
        error=$?
    done

    [ "x$error" = "x0" ]
SCRIPT

rc = delete.ssh(:host => dst.host,
                :cmds => delete_file,
                :err_msg => "Error deleting #{dst.path}",
                :nostdout => false,
                :nostderr => false)

exit(rc.code)
