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

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

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

    uri = onebex_uri + "/vms/#{vm_id}/cancel"

    rc = begin
        http_post_json(
            uri,
            {
                :MESSAGE => 'Backup cancelled'
            }
        )
    rescue StandardError
        # If the OneBEX server is down, the cancel is already done.
        exit(0)
    end

    unless rc.code.to_i == 200
        raise StandardError,
              "Unable to cancel VM #{vm_id} interactive backup: #{rc.body}"
    end
rescue StandardError => e
    STDERR.puts e.message

    exit(-1)
end

exit(0)
