#!/usr/bin/env ruby

# -------------------------------------------------------------------------- #
# Copyright 2002-2026, 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%%

$LOAD_PATH << RUBY_LIB_LOCATION

require 'json'
require 'net/http'
require 'rexml/document'
require 'uri'
require 'yaml'

require 'CommandManager'

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

TransferManager::Datastore.load_env

# ------------------------------------------------------------------------------
# HTTP helpers
# ------------------------------------------------------------------------------

def http_get(uri, open_timeout: 2, read_timeout: 5)
    Net::HTTP.start(
        uri.host,
        uri.port,
        :open_timeout => open_timeout,
        :read_timeout => read_timeout
    ) do |http|
        http.get(uri.request_uri)
    end
end

def http_post_json(uri, body = nil, open_timeout: 2, read_timeout: 5)
    req = Net::HTTP::Post.new(uri.request_uri)
    req['Content-Type'] = 'application/json'

    req.body = body.to_json unless body.nil?

    Net::HTTP.start(
        uri.host,
        uri.port,
        :open_timeout => open_timeout,
        :read_timeout => read_timeout
    ) do |http|
        http.request(req)
    end
end

# ------------------------------------------------------------------------------
# Finish every active OneBEX transfer for the VM as failed.
# ------------------------------------------------------------------------------

def finish_transfers(onebex_uri, vm_id)
    uri = onebex_uri + "/status?VM_ID=#{vm_id}"

    status_rc = http_get(uri)

    return unless status_rc.code.to_i == 200

    status = JSON.parse(status_rc.body)
    transfers = status.fetch('TRANSFERS', [])

    transfers.each do |transfer|
        transfer_id = transfer['TRANSFER_ID']

        next if transfer_id.nil?

        uri = onebex_uri + "/transfer/#{transfer_id}/finalize"

        rc = http_post_json(
            uri,
            {
                :SUCCESS => false,
                :MESSAGE => 'Backup cancelled'
            }
        )

        next if rc.code.to_i == 200

        raise StandardError,
              "Unable to finish transfer #{transfer_id}: #{rc.body}"
    end
end

# ------------------------------------------------------------------------------
# Finalize the VM-level OneBEX backup session.
#
# /vms/:vm_id/finish returns:
#   - 200 when no pending transfers remain
#   - 409 while transfers are still pending
#
# On each 409, retry transfer finalization because pending transfers may still be
# visible or new ones may appear while the backup action is being terminated.
# ------------------------------------------------------------------------------

def finish_vm_backup(onebex_uri, vm_id, retries: 10, sleep_time: 1)
    uri = onebex_uri + "/vms/#{vm_id}/finish"

    last_body = nil

    retries.times do
        finish_transfers(onebex_uri, vm_id)

        rc = http_post_json(uri)

        case rc.code.to_i
        when 200
            result = JSON.parse(rc.body)

            unless result['STATUS'] == 'finished'
                raise StandardError,
                      "Unexpected VM finish status for VM #{vm_id}: #{rc.body}"
            end

            return result

        when 409
            last_body = rc.body
            sleep sleep_time
            next

        else
            raise StandardError,
                  "Unable to finish VM #{vm_id} interactive backup: #{rc.body}"
        end
    end

    raise StandardError,
          "Timeout waiting for VM #{vm_id} transfers to finish: #{last_body}"
end

# ------------------------------------------------------------------------------
# Main
# ------------------------------------------------------------------------------

vm_xml  = STDIN.read

dir     = ARGV[0].split(':')
vm_uuid = ARGV[1]

begin
    xml_data = REXML::Document.new(vm_xml)

    vm_id = xml_data.elements['VM/ID'].text

    conf = YAML.load_file(
        File.expand_path('../../etc/onebex/onebex-server.conf', __dir__)
    )

    onebex_host = conf[:host].to_s
    onebex_port = conf[:port].to_i

    # If OneBEX is listening on all interfaces, use the TM endpoint host.
    onebex_host = dir[0] if ['0.0.0.0', 'localhost'].include?(onebex_host)

    onebex_uri = URI("http://#{onebex_host}:#{onebex_port}")

    # Kill the running interactive backup action.
    script = <<~EOS
        set -x -e -o pipefail; shopt -qs failglob
        (ps --no-headers -o pid,cmd -C ruby \\
        | awk '$0 ~ "(pre)?backup(_live)? .*#{vm_uuid} " { print $1 } END { print "\\0" }' || :) \\
        | (read -d '' PIDS
           [[ -n "$PIDS" ]] || exit 0                           # empty
           [[ -z "${PIDS//[[:space:][:digit:]]/}" ]] || exit -1 # !integers
           kill -s TERM $PIDS)
    EOS

    rc = LocalCommand.run '/bin/bash -s', nil, script

    if rc.code != 0
        raise StandardError,
              "Unable to stop interactive backup action: #{rc.stderr}"
    end

    # Finalize all active OneBEX transfers for this VM.
    finish_transfers(onebex_uri, vm_id)

    # Finalize the VM-level backup session.
    finish_vm_backup(onebex_uri, vm_id)
rescue StandardError => e
    STDERR.puts e.message

    exit(-1)
end

exit(0)
