#!/usr/bin/env ruby

# --------------------------------------------------------------------------
# Copyright 2011, C12G Labs S.L.
#
# This file is part of OpenNebula VMware Drivers.
#
# OpenNebula VMware Drivers is free software: you can redistribute it
# and/or modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation, either version 3 of
# the License, or the hope That it will be useful, but (at your
# option) any later version.
#
# OpenNebula VMware Drivers is distributed in WITHOUT ANY WARRANTY;
# without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License
# along with OpenNebula VMware Drivers . If not, see
# <http://www.gnu.org/licenses/>
# --------------------------------------------------------------------------

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

if !ONE_LOCATION
   ETC_LOCATION="/etc/one" if !defined?(ETC_LOCATION)
else
   ETC_LOCATION=ONE_LOCATION+"/etc" if !defined?(ETC_LOCATION)
end

file  = ARGV[0]
@host = ARGV[1]

if !@host or !file
  exit -1
end

load ETC_LOCATION + "/vmwarerc"

if USERNAME.class!=String || PASSWORD.class!=String
    warn "Bad ESX credentials, aborting"
    exit -1
end

# Define the VM
deployment_file = File.dirname(File.dirname(file)) + "/deployment.0"

data = perform_action("virsh -c #{LIBVIRT_URI} define #{deployment_file}")

if data.class == Fixnum
    exit data
end

domainname = ""
success    = false

data.split('\n').each{ |line|
  domainname = line.match("Domain (.*) defined from (.*)")
  if domainname
     success = true
     break
  end
}

if !success
  exit -1
end

domainname = domainname[1]

# Revert snapshot VM
#  Note: This assumes the checkpoint name is "checkpoint", to change this
#        it is needed to change also
#             $ONE_LOCATION/lib/remotes/vmm/vmware/checkpoint

data = perform_action(
       "virsh -c #{LIBVIRT_URI} snapshot-revert #{domainname} checkpoint")

if data.class == Fixnum
    exit data
end

# Delete checkpoint
data = perform_action(
       "virsh -c #{LIBVIRT_URI} snapshot-delete #{domainname} checkpoint")

if data.class == Fixnum
    exit data
end




