#!/usr/bin/env ruby

# -------------------------------------------------------------------------- #
# Copyright 2002-2024, 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.                                             #
#--------------------------------------------------------------------------- #

ONE_LOCATION = ENV['ONE_LOCATION']

if !ONE_LOCATION
    RUBY_LIB_LOCATION = '/usr/lib/one/ruby'
    GEMS_LOCATION     = '/usr/share/one/gems'
    SCRIPTS_LOCATION = '/usr/lib/one/oneswap/scripts'
else
    RUBY_LIB_LOCATION = ONE_LOCATION + '/lib/ruby'
    GEMS_LOCATION     = ONE_LOCATION + '/share/gems'
    SCRIPTS_LOCATION = ONE_LOCATION + '/lib/oneswap/scripts'
end

# %%RUBYGEMS_SETUP_BEGIN%%
if File.directory?(GEMS_LOCATION)
    real_gems_path = File.realpath(GEMS_LOCATION)
    if !defined?(Gem) || Gem.path != [real_gems_path]
        $LOAD_PATH.reject! {|l| l =~ /vendor_ruby/ }

        # Suppress warnings from Rubygems
        # https://github.com/OpenNebula/one/issues/5379
        begin
            verb = $VERBOSE
            $VERBOSE = nil
            require 'rubygems'
            Gem.use_paths(real_gems_path)
        ensure
            $VERBOSE = verb
        end
    end
end
# %%RUBYGEMS_SETUP_END%%

$LOAD_PATH << RUBY_LIB_LOCATION
$LOAD_PATH << RUBY_LIB_LOCATION + '/cli'

require 'command_parser'
require 'rbvmomi'
require 'one_helper/oneswap_helper'
require 'fileutils'
require 'webrick'
require 'openssl'
require 'socket'
require 'ipaddr'
require 'open3'
require 'rexml'
require 'yaml'
require 'cgi'

WORK_PATH = '/var/tmp'

CommandParser::CmdParser.new(ARGV) do
    usage '`oneswap` <command> [<args>] [<options>]'
    version OpenNebulaHelper::ONE_VERSION

    helper = OneSwapHelper.new
    normalize_config = lambda do |cfg|
        next cfg unless cfg.respond_to?(:transform_keys)

        cfg.transform_keys {|key| key.to_s.sub(/^:/, '').to_sym }
    end

    before_proc do
        helper.set_client(options)
    end

    ####################
    # Global Arguments #
    ####################
    set :option, CommandParser::OPTIONS + OpenNebulaHelper::CLIENT_OPTIONS

    VCENTER = {
        :name  => 'vcenter',
        :large => '--vcenter vCenter',
        :description => 'The vCenter hostname',
        :format => String
    }

    USER = {
        :name  => 'vuser',
        :large => '--vuser username',
        :description => 'The username to interact with vCenter',
        :format => String
    }

    PASS = {
        :name  => 'vpass',
        :large => '--vpass password',
        :description => 'The password for the user',
        :format => String
    }

    PORT = {
        :name  => 'port',
        :short => '-p port',
        :large => '--port port',
        :format => String,
        :description => 'vCenter API port, defaults to 443 (SSL) or 80'
    }

    AUTH_OPTS = [VCENTER, USER, PASS, PORT]

    #####################
    # Command Arguments #
    #####################

    NAME = {
        :name => 'name',
        :short => '-n text',
        :large => '--name text',
        :description => 'Filter by name containing text',
        :format => String
    }

    DATACENTER = {
        :name => 'datacenter',
        :short => '-d text',
        :large => '--datacenter text',
        :description => 'Filter by Datacenter name containing text',
        :format => String
    }

    CLUSTER = {
        :name => 'cluster',
        :short => '-c text',
        :large => '--cluster text',
        :description => 'Filter by Cluster name containing text',
        :format => String
    }

    STATE = {
        :name => 'state',
        :short => '-s vm_state',
        :large => '--state vm_state',
        :description => 'Filter VMs by their power state: [poweroff, running, suspended]',
        :format => String
    }

    NETWORK = {
        :name => 'network',
        :large => '--network id',
        :description => 'If a VCENTER_NETWORK_MATCH attribute in an OpenNebula does not match the name of a vCenter network, assign to this OpenNebula Network ID instead.',
        :format => String
    }

    NO_IP = {
        :name => 'skip_ip',
        :large => '--skip-ip',
        :description => 'Do not pull IP from vCenter to be created in OpenNebula'
    }

    NO_MAC = {
        :name => 'skip_mac',
        :large => '--skip-mac',
        :description => 'Do not pull MAC from vCenter to be created in OpenNebula'
    }

    PERSISTENT_IMG = {
        :name => 'persistent_img',
        :large => '--persistent-img',
        :description => 'Make the image disk persistent in OpenNebula'
    }

    GRAPHICS_TYPE = {
        :name => 'graphics_type',
        :large => '--graphics-type type',
        :description => 'The Graphics type to enable in OpenNebula. Options: [vnc, sdl, spice]',
        :format => String
    }

    GRAPHICS_LISTEN = {
        :name => 'graphics_listen',
        :large => '--graphics-listen ip',
        :description => 'The Graphics Listen on IP in OpenNebula. Graphics type required.',
        :format => String
    }

    GRAPHICS_PORT = {
        :name => 'graphics_port',
        :large => '--graphics-port port',
        :description => 'The Graphics Server port in OpenNebula. Graphics type required.',
        :format => String
    }

    GRAPHICS_KEYMAP = {
        :name => 'graphics_keymap',
        :large => '--graphics-keymap keymap',
        :description => 'The Graphics Keymap in OpenNebula. Graphics type required.',
        :format => String
    }

    GRAPHICS_PASSWORD = {
        :name => 'graphics_password',
        :large => '--graphics-password password',
        :description => 'The Graphics Password in OpenNebula. Graphics type required.',
        :format => String
    }

    GRAPHICS_COMMAND = {
        :name => 'graphics_command',
        :large => '--graphics-command command',
        :description => 'The Graphics Command in OpenNebula. Graphics type required.',
        :format => String
    }

    MEMORY_MAX = {
        :name => 'memory_max',
        :large => '--memory-max memorymb',
        :description => 'The Max Memory allowed in MB in OpenNebula. Memory Hot Add required in VMware.',
        :format => Integer
    }

    VCPU_MAX = {
        :name => 'vcpu_max',
        :large => '--vcpu-max vcpumax',
        :description => 'The Max vCPU allowed in integer format in OpenNebula. CPU Hot Add required in VMware.',
        :format => Integer
    }

    CPU = {
        :name => 'cpu',
        :large => '--cpu cpus',
        :description => 'The Physical CPU allowed in integer format in OpenNebula. Default is to match CPU cores in vCenter.',
        :format => Integer
    }

    VCPU = {
        :name => 'vcpu',
        :large => '--vcpu vcpus',
        :description => 'The vCPU allowed in integer format in OpenNebula. Default is to match CPU cores in vCenter',
        :format => Integer
    }

    IMG_WAIT = {
        :name => 'img_wait',
        :large => '--img-wait sec',
        :description => 'The amount of time to wait in seconds for the image to be created in OpenNebula. Default is 120 seconds',
        :format => Integer
    }

    DEV_PREFIX = {
        :name => 'dev_prefix',
        :large => '--dev-prefix sd',
        :description => 'The Dev Prefix to use on the disks in OpenNebula. ex: sd, hd, vd, xvd. Default is none',
        :format => String
    }

    DISABLE_CONTEXTUALIZATION = {
        :name => 'disable_contextualization',
        :large => '--disable-contextualization',
        :description => 'Remove default contextualization options in OpenNebula. Default is for Network and SSH contextualization to be enabled.'
    }

    CPU_MODEL = {
        :name => 'cpu_model',
        :large => '--cpu-model model_type',
        :description => 'Set a Specific CPU model in OpenNebula. Default is None',
        :format => String
    }

    DATASTORE = {
        :name => 'datastore',
        :large => '--datastore id',
        :description => 'Create images in the Image Datastore with this ID, Default: 1',
        :format => String
    }

    WORK_DIR = {
        :name => 'work_dir',
        :short => '-w directory',
        :large => '--work-dir directory',
        :description => "Directory where disk conversion takes place, will make subdir for each VM, Default: #{WORK_PATH}",
        :format => String
    }

    FORMAT = {
        :name => 'format',
        :short => '-f type',
        :large => '--format type',
        :description => 'Disk format [ qcow2 | raw ], Default: qcow2',
        :format => String
    }

    DELETE = {
        :name => 'delete',
        :large => '--delete-after',
        :description => 'Removes the leftover conversion directory in the working directory which contains the converted VM disk'\
                        's and descriptor files'
    }

    CONTEXT = {
        :name => 'context',
        :large => '--context-package /path/to/context/',
        :description => 'Directory with the context packages for guest OS injection, will search by default in /usr/share/one/context',
        :format => String
    }

    SKIP_CONTEXT = {
        :name => 'skip_context',
        :large => '--skip-context',
        :description => 'Skips the injection of the context package'
    }

    INJECT_DNS = {
        :name => 'inject_dns',
        :large => '--inject-dns host|ip',
        :description => "Pass 'host' to copy the host's /etc/resolv.conf "\
                        "or pass one or more comma-separated DNS server IPs (e.g. 8.8.8.8 or 8.8.8.8,1.1.1.1) "\
                        "to generate a custom resolv.conf.",
        :format => String
    }

    CONTEXT_MIN_FREE = {
        :name => 'context_min_free',
        :large => '--context-min-free MB',
        :description => 'Minimum free space (in MB) required on the guest root filesystem before context '\
                        'injection. If free space is below this threshold oneswap warns and skips injection '\
                        '(or fails the disk conversion with --context-fail-on-low-space). Set to 0 to disable '\
                        'the check. Default: 1024',
        :format => Integer
    }

    CONTEXT_FAIL_LOW_SPACE = {
        :name => 'context_fail_on_low_space',
        :large => '--context-fail-on-low-space',
        :description => 'Fail the disk conversion instead of warning and skipping when the guest root '\
                        'filesystem free space is below --context-min-free.'
    }

    CONTEXT_TIMEOUT = {
        :name => 'context_timeout',
        :large => '--context-timeout SECONDS',
        :description => 'Maximum time (in seconds) allowed for each context injection command before it is '\
                        'aborted. Set to 0 to disable. Default: 600',
        :format => Integer
    }

    ESXI = {
        :name => 'esxi_ip',
        :large => '--esxi ip',
        :description => 'Transfer directly from ESXi host instead using provided IP, may be useful if vCenter download is slow. '\
                        'Requires SSH access to ESXi host. The vCenter credentials are required to gather other information abou'\
                        't the virtual machine.',
        :format => String
    }

    ESXI_USER = {
        :name => 'esxi_user',
        :large => '--esxi-user username',
        :description => 'ESXi username for SSH login, default: root',
        :format => String
    }

    ESXI_PASS = {
        :name => 'esxi_pass',
        :large => '--esxi-pass password',
        :description => 'ESXi password for SSH login. Required for direct ESXi transfer.',
        :format => String
    }

    VDDK = {
        :name => 'vddk_path',
        :large => '--vddk /path/to/vddk/',
        :description => 'Full path to the VDDK library, required for VDDK based transfer',
        :format => String
    }

    DELTA = {
        :name => 'delta',
        :large => '--delta',
        :description => 'Convert the VM with reduced downtime using snapshots. Requires ESXi host paswordless root SSH access.'
    }

    DELTA_PREPARE = {
        :name => 'delta_prepare',
        :large => '--delta-prepare',
        :description => 'Run only the delta base phase and persist state for a later dry-run or commit.'
    }

    DELTA_COMMIT = {
        :name => 'delta_commit',
        :large => '--delta-commit',
        :description => 'Run only the delta final phase from prepared state.'
    }

    DELTA_CLEANUP = {
        :name => 'delta_cleanup',
        :large => '--delta-cleanup',
        :description => 'Clean up prepared delta state, snapshot, and temporary files.'
    }

    DRY_RUN = {
        :name => 'dry_run',
        :large => '--dry-run',
        :description => 'Estimate conversion time without creating snapshots, images, or templates.'
    }

    BENCHMARK_IMPORT = {
        :name => 'benchmark_import',
        :large => '--benchmark-import',
        :description => 'Benchmark OpenNebula image import during --dry-run using a temporary image.'
    }

    BENCHMARK_EXPORT = {
        :name => 'benchmark_export',
        :large => '--benchmark-export',
        :description => 'Benchmark source export during regular --dry-run using a temporary datastore file.'
    }

    CUSTOM = { # not sure what to call this actually
        :name => 'custom_convert',
        :large => '--custom',
        :description => 'Forces the use of OpenNebula\'s custom conversion process. This will skip virt-v2v conversion attempts.'
    }

    FALLBACK = {
        :name => 'fallback',
        :large => '--fallback',
        :description => 'If the virt-v2v conversion fails, attempt the OpenNebula Custom Conversion process.'
    }

    HYBRID = {
        :name => 'hybrid',
        :large => '--hybrid',
        :description => 'Download the disk using rbvmomi2, then convert the vm using virt-v2v locally.'
    }

    DOWNLOAD_STRIPES = {
        :name => 'download_stripes',
        :large => '--download-stripes N',
        :description => 'Parallel HTTP range downloads for hybrid datastore transfers only. Default: 1',
        :format => Integer
    }

    WIN_GA = {
        :name => 'qemu_ga_win',
        :large => '--win-qemu-ga /path/to/iso',
        :description => 'Install QEMU Guest Agent to a Windows guest',
        :format => String
    }

    LNX_GA = {
        :name => 'qemu_ga_linux',
        :large => '--qemu-ga',
        :description => 'Install qemu-guest-agent package to a Linux guest, useful with --custom or --fallback'
    }

    VIRTIO = {
        :name => 'virtio_path',
        :large => '--virtio /path/to/iso',
        :description => 'Full path of the win-virtio ISO file. Required to inject virtio drivers to Windows Guests',
        :format => String
    }

    RHSRVANY = {
        :name => 'virt_tools',
        :large => '--virt-tools /path/to/virt-tools',
        :description => 'Path to the directory containing rhsrvany.exe, defaults to /usr/local/share/virt-tools. See https://github.com/rwmjones/rhsrvany.',
        :format => String
    }

    ONE_CLUSTER = {
        :name => 'one_cluster',
        :large => '--one-cluster id',
        :description => 'ID of the Cluster in OpenNebula the VM Template should be scheduled to',
        :format => Integer
    }

    ONE_HOST = {
        :name => 'one_host',
        :large => '--one-host id',
        :description => 'ID of the Host in OpenNebula the VM Template should be scheduled to',
        :format => Integer
    }

    ONE_DS = {
        :name => 'one_datastore',
        :large => '--one-sys-ds id',
        :description => 'ID of the System Datastore in OpenNebula the VM should be scheduled to',
        :format => Integer
    }

    ONE_DS_CLUSTER = {
        :name => 'one_datastore_cluster',
        :large => '--one-ds-cluster id',
        :description => 'ID of the Cluster in OpenNebula the System Datastore should be scheduled to',
        :format => Integer
    }

    V2V_PATH = {
        :name => 'v2v_path',
        :large => '--v2v-path /path/to/custom/v2v',
        :description => 'Path to custom virt-v2v executable if necessary',
        :format => String
    }

    LIBGUESTFS_PATH = {
        :name => 'libguestfs_path',
        :large => '--libguestfs-path /path/to/libguestfs-appliance',
        :description => 'Path to prebuilt libguestfs appliance for non-root execution',
        :format => String
    }

    HTTP_TRANSFER = {
        :name => 'http_transfer',
        :large => '--http-transfer',
        :description => 'Transfer images over HTTP, for use with a separate oneswap server'
    }

    HTTP_HOST = {
        :name => 'http_host',
        :large => '--http-host host',
        :description => 'IP of this machine to transfer images over HTTP, will also try to detect it if not specified',
        :format => String
    }

    HTTP_PORT = {
        :name => 'http_port',
        :large => '--http-port port',
        :description => 'Port to transfer images over HTTP, for use with a separate oneswap server. Default: 29869',
        :format => Integer
    }

    ALLOW_LOCAL_PATH_REMOTE = {
        :name => 'allow_local_path_remote',
        :large => '--allow-local-path-remote',
        :description => 'Allow local PATH image allocation when OpenNebula endpoint appears remote. Use only when work_dir is shared at the same path.'
    }

    CONF_FILE = {
        :name => 'config_file',
        :large => '--config-file /path/to/custom/config.yaml',
        :description => 'Path to custom Configuration File, default is /etc/one/oneswap.yaml',
        :format => String
    }

    OVA = {
        :name => 'ova',
        :large => '--ova ova.ova',
        :description => 'File name or path to OVA files folder in case the guest was exported as a "Folder of files" or if the OVA has been previously unpacked',
        :format => String
    }

    VMDK = {
        :name => 'vmdk',
        :large => '--vmdk vmdk.vmdk',
        :description => 'Full VMDK file path to import.',
        :format => String
    }

    ROOT = {
        :name => 'root',
        :large => '--root option',
        :description => 'Choose the root filesystem to be converted. Can be ask, single, first or /dev/sdX',
        :format => String
    }

    CLONE = {
        :name => 'clone',
        :large => '--clone',
        :description => 'Trigger a VM full clone and convert that clone without requiring to poweroff the original VM'
    }

    REMOVE_VMTOOLS = {
        :name => 'remove_vmtools',
        :large => '--remove-vmtools',
        :description => 'Add contextualization script to force remove VMware tools from the VM'
    }

    SKIP_PRECHEKS = {
        :name => 'skip_prechecks',
        :large => '--skip-prechecks',
        :description => 'Skip OpenNebula system prechecks before conversion.'
    }

    ACCEPT_CERT = {
        :name => 'accept_cert',
        :large => '--accept-cert',
        :description => 'Accept SSL certificates for vCenter connections'
    }

    UEFI_PATH = {
        :name => 'uefi_path',
        :large => '--uefi-path /path/to/uefi',
        :description => 'Path to the UEFI file to be configured in the VM template.',
        :format => String

    }

    UEFI_SEC_PATH = {
        :name => 'uefi_sec_path',
        :large => '--uefi-sec-path /path/to/uefi.secboot',
        :description => 'Path to the UEFI Secure file to be configured in the VM template.',
        :format => String

    }

    ONE_USER = {
        :name => 'one_user',
        :large => '--one-user user',
        :description => 'Assign migrated objects (images, VM template) to this OpenNebula user (name or numeric ID)',
        :format => String
    }

    ONE_GROUP = {
        :name => 'one_group',
        :large => '--one-group group',
        :description => 'Assign migrated objects (images, VM template) to this OpenNebula group (name or numeric ID)',
        :format => String
    }

    VM_LIST = {
        :name  => 'vm_list',
        :large => '--vm-list /path/to/vms.txt',
        :description => 'Path to a file containing one VM name per line for batch conversion. '\
                        'Empty lines and lines starting with # are ignored.',
        :format => String
    }

    VMS = {
        :name  => 'vm_names',
        :large => '--vms vm1,vm2,...',
        :description => 'Comma-separated list of VM names for batch conversion.',
        :format => String
    }

    ESXI_OPTS = [ESXI, ESXI_USER, ESXI_PASS]
    V2V_OPTS = [V2V_PATH, LIBGUESTFS_PATH, WORK_DIR, FORMAT, VIRTIO, WIN_GA, LNX_GA, DELETE, VDDK, RHSRVANY, ROOT]
    HTTP_OPTS = [HTTP_TRANSFER, HTTP_HOST, HTTP_PORT, ALLOW_LOCAL_PATH_REMOTE]

    LIST_OPTS    = [NAME, DATACENTER, CLUSTER, STATE, ACCEPT_CERT] + AUTH_OPTS
    CONVERT_OPTS = [NETWORK, NO_IP, NO_MAC, DATASTORE, CONTEXT, FALLBACK, CUSTOM, HYBRID, DOWNLOAD_STRIPES, DELTA, DELTA_PREPARE, DELTA_COMMIT, DELTA_CLEANUP, DRY_RUN, BENCHMARK_IMPORT, BENCHMARK_EXPORT, V2V_PATH, CONF_FILE, IMG_WAIT, DEV_PREFIX,
                    CPU_MODEL, GRAPHICS_TYPE, GRAPHICS_LISTEN, GRAPHICS_PORT, GRAPHICS_KEYMAP, GRAPHICS_PASSWORD, GRAPHICS_COMMAND, DISABLE_CONTEXTUALIZATION,
                    PERSISTENT_IMG, MEMORY_MAX, VCPU_MAX, CPU, VCPU, ONE_DS, ONE_DS_CLUSTER, ONE_CLUSTER, ONE_HOST, CLONE, REMOVE_VMTOOLS,
                    SKIP_PRECHEKS, UEFI_PATH, UEFI_SEC_PATH, INJECT_DNS, CONTEXT_MIN_FREE, CONTEXT_FAIL_LOW_SPACE, CONTEXT_TIMEOUT,
                    ACCEPT_CERT, ONE_USER, ONE_GROUP, VM_LIST, VMS] + AUTH_OPTS + ESXI_OPTS + V2V_OPTS + HTTP_OPTS
    IMPORT_OPTS = [OVA, VMDK, DATASTORE, NETWORK, SKIP_CONTEXT, REMOVE_VMTOOLS, UEFI_PATH,
                   UEFI_SEC_PATH, INJECT_DNS, CONTEXT_MIN_FREE, CONTEXT_FAIL_LOW_SPACE, CONTEXT_TIMEOUT,
                   ONE_USER, ONE_GROUP] + V2V_OPTS

    ############################################################################
    # list resources
    ############################################################################
    list_desc = <<-EOT.unindent
        Show a list with vCenter objects, default to VM

        Examples:
           - listing all VMs:

             oneswap list vms

           - listing available Clusters:

             oneswap list clusters

           - listing available vms in a Datacenter and Cluster:

             oneswap list vms --datacenter DCName --cluster Cluster2

    EOT

    command :list, list_desc, :object, :options => LIST_OPTS do
        begin
            options[:config_file] ||= '/etc/one/oneswap.yaml'
            if options[:config_file] && !File.exist?(options[:config_file])
                raise "Unable to find the config file at #{options[:config_file]}"
            end

            cfg_file = normalize_config.call(YAML.load_file(options[:config_file])) if File.exist?(options[:config_file])
            options.merge!(cfg_file) if cfg_file
            options[:object] = args[0]
            helper.parse_opts(options)
            helper.list(options)
        rescue StandardError => e
            STDERR.puts e.message
            exit 1
        end

        0
    end

    conv_desc = <<-EOT.unindent
        Convert a vCenter Virtual Machine

        Examples:
            VOPTS='--vcenter 12.34.56.78 --vuser Administrator@vsphere.local --vpass changeme123'

            - Convert a virtual machine:

            oneswap convert vm-1234 $VOPTS [--fallback|--custom] [--network ID] [--datacenter ID]

            - Convert a virtual machine from ESXi directly:

            oneswap convert vm-1234 $VOPTS --esxi 12.34.56.79 --esxi_pass changeme123 [--esxi_user root]

            - Convert a vCenter virtual machine utilizing the proprietary VDDK library(faster transfer usually):

            oneswap convert vm-1234 $VOPTS --vddk /path/to/vddk-lib

            - Convert using OpenNebula Custom Conversion (useful for distributions which are not supported or fail to convert)
            You can also define --fallback instead of --custom, which will first attempt virt-v2v style, then fallback to custom.

            oneswap convert vm-1234 $VOPTS --custom

            - Convert a batch of VMs from a list file (one VM name per line, # for comments):

            oneswap convert --vm-list vms.txt $VOPTS [--fallback|--custom|--hybrid]

            - Convert a batch of VMs specified inline (comma-separated):

            oneswap convert --vms vm-web-01,vm-db-01,vm-app-01 $VOPTS [--fallback|--custom|--hybrid]

    EOT

    command :convert, conv_desc, [:vm_name, nil], :options => CONVERT_OPTS do
        begin
            if options[:config_file] && !File.exist?(options[:config_file])
                puts "Unable to find the config file at #{options[:config_file]}"
            end
            options[:config_file] ||= '/etc/one/oneswap.yaml'
            cfg_file = normalize_config.call(YAML.load_file(options[:config_file])) if File.exist?(options[:config_file])
            options.merge!(cfg_file) if cfg_file

            if (options[:download_stripes] || 1).to_i > 1 && !options[:hybrid]
                raise '--download-stripes N > 1 requires --hybrid.'
            end

            if (options[:delta_prepare] || options[:delta_commit] || options[:delta_cleanup]) && !options[:delta]
                raise '--delta-prepare, --delta-commit, and --delta-cleanup require --delta.'
            end
            delta_phase_count = [options[:delta_prepare], options[:delta_commit], options[:delta_cleanup]].count {|v| v }
            if delta_phase_count > 1
                raise '--delta-prepare, --delta-commit, and --delta-cleanup cannot be combined.'
            end
            if options[:dry_run] && (options[:delta_prepare] || options[:delta_commit] || options[:delta_cleanup])
                raise '--dry-run cannot be combined with --delta-prepare, --delta-commit, or --delta-cleanup.'
            end
            if options[:benchmark_import] && !options[:dry_run]
                raise '--benchmark-import requires --dry-run.'
            end
            if options[:benchmark_export] && !options[:dry_run]
                raise '--benchmark-export requires --dry-run.'
            end
            if options[:benchmark_export] && options[:delta]
                raise '--benchmark-export is only supported for regular non-delta dry-run.'
            end

            if options[:delta]
                incompatible_delta = []
                incompatible_delta << '--custom' if options[:custom_convert]
                incompatible_delta << '--hybrid' if options[:hybrid]
                incompatible_delta << '--fallback' if options[:fallback]
                incompatible_delta << '--vddk' if options[:vddk_path]
                incompatible_delta << '--esxi' if options[:esxi_ip]

                if !incompatible_delta.empty?
                    raise "--delta cannot be combined with #{incompatible_delta.join(', ')}."
                end
            end

            raise 'ESXi Transfer requires at least IP and Password' if options[:esxi_ip] && options[:esxi_pass].nil?
            raise 'ESXI and VDDK cannot be used at same time, recommend VDDK.' if options[:esxi_ip] && options[:vddk_path]
            if options[:hybrid] && (options[:custom_convert] || options[:esxi_ip] || options[:vddk_path])
                raise 'Cannot use Hybrid option with Custom, ESXi, or VDDK options.'
            end
            if options[:virtio_path] && !options[:virtio_path].to_s.strip.empty? && !File.exist?(options[:virtio_path])
                raise "Windows VirtIO ISO cannot be found at #{options[:virtio_path]}"
            end
            if options[:qemu_ga_win] && !File.exist?(options[:qemu_ga_win])
                raise "Windows QEMU Guest Agent ISO cannot be found at #{options[:qemu_ga_win]}"
            end

            if (options[:virtio_path] || options[:qemu_ga_win]) && options[:custom_convert]
                vcv = `virt-customize --version`.split(' ')[1]
                if Gem::Version.new(vcv) <= Gem::Version.new('1.49.9')
                    puts 'Windows VirtIO and QEMU Guest Agent require virt-customize >= 1.49.9.'
                    options[:virtio_path] = options[:qemu_ga_win] = false
                end
            end
            if options[:fallback] && options[:custom_convert]
                raise 'Cannot define both --fallback and --custom.'
            end

            options[:work_dir]         ||= WORK_PATH
            options[:format]           ||= 'qcow2'
            options[:context]          ||= '/usr/share/one/context'
            options[:esxi_user]        ||= 'root'
            options[:datastore]        ||= 1
            options[:virt_tools]       ||= '/usr/local/share/virt-tools'
            options[:v2v_path]         ||= 'virt-v2v'
            options[:remove_vmtools]   ||= false
            options[:clone]            ||= false
            options[:skip_prechecks]   ||= false
            options[:context_min_free] ||= 1024
            options[:context_timeout]  ||= 600
            options[:download_stripes] ||= 1
            options[:dry_run_source_export_mib_s] ||= 80
            options[:dry_run_qcow2_conversion_mib_s] ||= 120
            options[:dry_run_target_import_mib_s] ||= 80
            options[:dry_run_delta_os_morph_seconds] ||= 480
            options[:dry_run_guest_customization_seconds] ||= 180
            options[:dry_run_import_benchmark_size_mib] ||= 4096
            options[:dry_run_source_benchmark_size_mib] ||= 1024

            if options[:http_transfer]
                options[:http_host] ||= Socket.ip_address_list.detect do |addrinfo|
                    addrinfo.ipv4? && !addrinfo.ipv4_loopback?
                end&.ip_address
                if options[:http_host].nil?
                    raise 'Unable to find an IP address for the host'
                end

                options[:http_port] ||= 29869
            else
                if options[:endpoint] && !options[:allow_local_path_remote]
                    raise 'Using alternative OpenNebula endpoint requires HTTP Transfer'
                end
            end

            vm_name  = args[0]
            vm_list  = options[:vm_list]
            vm_names = options[:vm_names]

            modes = [vm_name, vm_list, vm_names].compact
            if modes.size > 1
                raise 'Specify only one of: positional VM name, --vms, or --vm-list.'
            end
            raise 'Provide a VM name, --vms vm1,vm2,..., or --vm-list <file>.' if modes.empty?

            if vm_list
                exit helper.convert_batch(vm_list, options)
            elsif vm_names
                names = vm_names.split(',').map(&:strip).reject(&:empty?)
                raise '--vms requires at least one VM name' if names.empty?
                exit helper.convert_vm_list(names, options)
            else
                helper.convert(vm_name, options)
            end
        rescue ConversionError
            exit 1
        rescue StandardError => e
            STDERR.puts e.message
            exit 1
        end

        0
    end

    import_desc = <<-EOT.unindent
        Import an OVA as VM or VMDK as Image file exported from VMware

        Examples:
           - import VM from an OVA file:

             oneswap import --ova OVA.ova

           - import VM from an OVF file:

             oneswap import --ova /path/to/files

           - import Image from an VMDK file:

             oneswap import --vmdk disk.vmdk
    EOT

    command :import, import_desc, :options => IMPORT_OPTS do
        begin
            if options[:config_file] && !File.exist?(options[:config_file])
                puts "Unable to find the config file at #{options[:config_file]}"
            end

            options[:config_file] ||= '/etc/one/oneswap.yaml'
            cfg_file = normalize_config.call(YAML.load_file(options[:config_file])) if File.exist?(options[:config_file])
            options.merge!(cfg_file) if cfg_file

            raise 'ESXi Transfer requires at least IP and Password' if options[:esxi_ip] && options[:esxi_pass].nil?
            raise 'ESXI and VDDK cannot be used at same time, recommend VDDK.' if options[:esxi_ip] && options[:vddk_path]
            if options[:hybrid] && (options[:custom_convert] || options[:esxi_ip] || options[:vddk_path])
                raise 'Cannot use Hybrid option with Custom, ESXi, or VDDK options.'
            end
            if options[:virtio_path] && !options[:virtio_path].to_s.strip.empty? && !File.exist?(options[:virtio_path])
                raise "Windows VirtIO ISO cannot be found at #{options[:virtio_path]}"
            end
            if options[:qemu_ga_win] && !File.exist?(options[:qemu_ga_win])
                raise "Windows QEMU Guest Agent ISO cannot be found at #{options[:qemu_ga_win]}"
            end

            if (options[:virtio_path] || options[:qemu_ga_win]) && options[:custom_convert]
                vcv = `virt-customize --version`.split(' ')[1]
                if Gem::Version.new(vcv) <= Gem::Version.new('1.49.9')
                    puts 'Windows VirtIO and QEMU Guest Agent require virt-customize >= 1.49.9.'
                    options[:virtio_path] = options[:qemu_ga_win] = false
                end
            end

            options[:work_dir]         ||= WORK_PATH
            options[:format]           ||= 'qcow2'
            options[:context]          ||= '/usr/share/one/context/'
            options[:datastore]        ||= 1
            options[:virt_tools]       ||= '/usr/local/share/virt-tools'
            options[:v2v_path]         ||= 'virt-v2v'
            options[:root]             ||= 'first'
            options[:remove_vmtools]   ||= false
            options[:context_min_free] ||= 1024
            options[:context_timeout]  ||= 600

            helper.import(options)
        rescue StandardError => e
            STDERR.puts e.message
            exit 1
        end
    end
end
