#!/usr/bin/env ruby

# --------------------------------------------------------------------------
# Copyright 2010, 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/>
# --------------------------------------------------------------------------

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

if !@host or !deployment_file
    exit -1
end

if !ONE_LOCATION
        VMWARERC_LOCATION="/etc/one/vmwarerc"
else
        VMWARERC_LOCATION=ONE_LOCATION+"/etc/vmwarerc"
end
load VMWARERC_LOCATION

# Define the VM
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] 

# Start the VM
data = perform_action("virsh -c #{LIBVIRT_URI} start #{domainname}")

if data.class == Fixnum
    exit data
end

definedname = domainname
domainname  = ""
success     = false

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

if !success
  exit -1
end

if definedname != domainname[1]
  exit -1
else
  puts definedname
end
