#!/usr/bin/env ruby

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

# mkimage size format host:remote_system_ds/disk.i vmid dsid
#   - size in MB of the image
#   - format for the image
#   - host is the target host to deploy the VM
#   - remote_system_ds is the path for the system datastore in the host
#   - vmid is the id of the VM
#   - dsid is the target datastore (0 is the system datastore)

ONE_LOCATION=ENV["ONE_LOCATION"] if !defined?(ONE_LOCATION)

if !ONE_LOCATION
    RUBY_LIB_LOCATION="/usr/lib/one/ruby" if !defined?(RUBY_LIB_LOCATION)
else
    RUBY_LIB_LOCATION=ONE_LOCATION+"/lib/ruby" if !defined?(RUBY_LIB_LOCATION)
end

$: << RUBY_LIB_LOCATION
$: << File.dirname(__FILE__)

require 'vcenter_driver'

size               = ARGV[0]
path               = ARGV[2]
vmid               = ARGV[3]
dsid               = ARGV[4]

check_valid size, "size"
check_valid path, "path"
check_valid vmid, "vmid"
check_valid dsid, "dsid"

hostname, img_name = path.split(":")
disk_id  = img_name.split(".")[-1]

# Get host ID
host = VCenterDriver::VIHelper.find_by_name(OpenNebula::HostPool, hostname)
host_id = host['ID']

# Get datastore ref
one_ds = VCenterDriver::VIHelper.one_item(OpenNebula::Datastore, dsid)
ds_ref = one_ds['TEMPLATE/VCENTER_DS_REF']

# Get one_vm
one_vm = VCenterDriver::VIHelper.one_item(OpenNebula::VirtualMachine, vmid)

# Adapter and disk type from one_vm
adapter_type = one_vm["/VM/TEMPLATE/DISK[DISK_ID=#{disk_id}]/VCENTER_ADAPTER_TYPE"] ||
               VCenterDriver::VIHelper.get_default("IMAGE/TEMPLATE/VCENTER_ADAPTER_TYPE")
disk_type = one_vm["/VM/TEMPLATE/DISK[DISK_ID=#{disk_id}]/VCENTER_DISK_TYPE"] ||
            VCenterDriver::VIHelper.get_default("IMAGE/TEMPLATE/VCENTER_DISK_TYPE")

check_valid adapter_type, "adapter_type"
check_valid disk_type, "disk_type"

# Volatile images dir from one_vm
ds_volatile_dir = one_vm["/VM/TEMPLATE/DISK[DISK_ID=#{disk_id}]/VCENTER_DS_VOLATILE_DIR"] ||
            "one-volatile"

begin
    vi_client = VCenterDriver::VIClient.new_from_host(host_id)

    img_name = "#{ds_volatile_dir}/#{vmid}/one-#{vmid}-#{disk_id}"

    ds_vc = VCenterDriver::Storage.new_from_ref(ds_ref, vi_client)

    if ds_vc.class == VCenterDriver::Datastore
        ds_vc.create_virtual_disk(img_name, size, adapter_type, disk_type)
    end

rescue Exception => e
    message = "Error creating virtual disk in #{ds_vc['name']}."\
              " Reason: #{e.message}\n#{e.backtrace}"
    STDERR.puts error_message(message)
    exit -1
ensure
    vi_client.close_connection if vi_client
end
