#!/usr/bin/env ruby

# ---------------------------------------------------------------------------- #
# Copyright 2010-2011, C12G Labs S.L                                           #
#                                                                              #
# 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 !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

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

if !@host or !deploy_id
    exit -1
end

load ETC_LOCATION + "/vmwarerc"

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

data = perform_action("virsh -c #{LIBVIRT_URI} shutdown #{deploy_id}")

if data.class == Fixnum
    exit data
end

begin
    data = perform_action("virsh -c #{LIBVIRT_URI} list")
    if data.class == Fixnum
        exit data
    end
    sleep 2
end while data.match(deploy_id)

data = perform_action("virsh -c #{LIBVIRT_URI} undefine #{deploy_id}")

if data.class == Fixnum
    exit data
end



