#!/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} --readonly dominfo #{deploy_id}")

 if data.class == Fixnum
     puts "STATE=d"
     exit 0
 end

state = ""

data.split('\n').each{ |line|
  state = line.match("^State: (.*)")

  if state
     state = state[1].strip
     break
  end
}

state_short = ""

case state
    when "running","blocked","shutdown","dying"
        state_short = 'a'
    when "paused"
        state_short = 'p'
    when "crashed"
        state_short = 'c'
    else
        state_short = 'd'
end

puts "STATE=#{state_short}"



