#!/usr/bin/env ruby

# -------------------------------------------------------------------------- #
# Copyright 2002-2012, OpenNebula Project Leads (OpenNebula.org)             #
#                                                                            #
# 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 !ONE_LOCATION
    RUBY_LIB_LOCATION="/usr/lib/one/ruby"
else
    RUBY_LIB_LOCATION=ONE_LOCATION+"/lib/ruby"
end

$: << RUBY_LIB_LOCATION
$: << RUBY_LIB_LOCATION+"/cli"

require 'command_parser'
require 'ozones_helper/zones_helper.rb'


class Hash
  def self.transform_keys_to_strings(value)
    return value if not value.is_a?(Hash)
    hash = value.inject({}){|memo,(k,v)| memo[k.to_s] = Hash.transform_keys_to_strings(v); memo}
    return hash
  end
end

cmd=CommandParser::CmdParser.new(ARGV) do
    usage "`onezone` <command> [<args>] [<options>]"
    version OpenNebulaHelper::ONE_VERSION

    set :format, :zoneid, "Zone ID" do |arg|
        arg.match(/^[0123456789]+$/) ? [0,arg] : [-1]
    end

    ########################################################################
    # Global Options
    ########################################################################
    set :option, CommandParser::OPTIONS

    begin
        helper = ZonesHelper.new "zone"
    rescue Exception => e
        warn e.message
        exit -1
    end

    command :create, 'Create a new Zone', :file do
        helper.create_resource(args[0])
    end

    show_desc = <<-EOT.unindent
        Show information of a particular Zone
        Available resources: host, vm, image, vnet, vmtemplate,
                             user, cluster, datastore
        Examples:
          onezone show 4
          onezone show 4 host
    EOT

    command :show, show_desc, :zoneid, [:resource, nil],
    :options => OZonesHelper::JSON do
        zone = helper.show_resource(args[0],options)[1]

        #manually print here
        if options[:json]
            puts zone
        end

        if !args[1] then next 0 end

        case args[1]
        when "host"
            aux_helper  = OneHostHelper.new
        when "vm"
            aux_helper  = OneVMHelper.new
        when "image"
            aux_helper  = OneImageHelper.new
        when "vnet"
            aux_helper  = OneVNetHelper.new
        when "vmtemplate"
            aux_helper  = OneTemplateHelper.new
        when "user"
            aux_helper  = OneUserHelper.new
        when "cluster"
            aux_helper  = OneClusterHelper.new
        when "datastore"
            aux_helper  = OneDatastoreHelper.new
        else
            puts "\n:!: Pool #{args[1]} doesn't exist or is not supported\n\n"
            next 0
        end

        pool_hash_data = helper.get_resource_pool("zone", args[0], args[1],
                                                  options)
        if pool_hash_data[0] != 0
            puts "\nError retrieving information for pool #{args[1]}. Reason: " + pool_hash_data[1] + "\n\n"
            next 0
        end

        if !pool_hash_data[1]
            next 0
        end

        if options[:json]
            puts pool_hash_data[1]
            next 0
        end

        if pool_hash_data[1].is_a?(Hash)
            pool_hash_data[1]=[Hash.transform_keys_to_strings(pool_hash_data[1])]
        else
            pool_hash_data[1].each{|hash| hash.replace(Hash.transform_keys_to_strings(hash))}
        end

        puts
        str_h1="%-61s"
        CLIHelper.print_header(str_h1 % ["ZONE VIEW - #{args[1]}"],false)

        table = aux_helper.format_pool(options)
        table.show(pool_hash_data[1])

        0
    end

    command :list, 'Lists Zones in the pool', :options=>OZonesHelper::JSON do
        helper.list_pool(options)
    end

    command :delete, 'Deletes a Zone', :zoneid do
        helper.delete_resource(args[0],options)
    end
end
