#!/usr/bin/perl -w
###############################################################################
# (c) 2010 - Eaton Power Quality
#
# This scripts allows users to perform a Shutdown on an VMware ESXi Server 
# with the vMA for IPP
# example:
# ./shutdownESXi.pl --server $server --username $username --password $password
###############################################################################

#---------Start of Patch------------------#
#Issue Known => http://www.vmware.com/support/developer/vcli/vcli501/vsp5_501_vcli_relnotes.html
#Search "version unavailable"
my $lwpversion= "$LWP::UserAgent::VERSION";
my ($major, $minor) = split (/\./, $LWP::UserAgent::VERSION);
if(($major <  6))
{
  #Under 6     
  printf "LWP::UserAgent version is under 6\n";
  $ENV{PERL_LWP_SSL_VERIFY_HOSTNAME} = 0; 
}
elsif( ($major >= 6)&& ($minor <04))
{
  #Above 6 under 04
  printf "LWP::UserAgent version is above 6 an under 6.04\n";
  $ENV{PERL_LWP_SSL_VERIFY_HOSTNAME} = 0;
}
else
{
  #Above 6
  printf "LWP::UserAgent version number above 6.04\n";
  printf "Actual version is: $lwpversion\n";
}
#----------End of Patch------------#

use strict;
use warnings;
use VMware::VIRuntime;
use VMware::VILib;

my %opts = (
	server => {
		type => "=s",
		help => "IP name or adress of the ESX/ESXi server",
		required => 1,
	},

	username => {
		type => "=s",
		help => "Name of the ESX/ESXi administrator (ex: root)",
		required => 1,
	},
	password => {
		type => "=s",
		help => "Password of the administrator",
		required => 1,
	}
);
      
# Validate options, and connect to the server
Opts::add_options(%opts);
Opts::parse();
Opts::validate();
Util::connect();

# Obtain all inventory objects of the specified type
my $entity_type = "HostSystem";
my $entity_views = Vim::find_entity_views(view_type => $entity_type);

# Process the findings
foreach my $entity_view (@$entity_views) {
      my $entity_name = $entity_view->name;
      $entity_view->ShutdownHost(force => 1); 
      #if force => 0 the Host must be in maintenance mode otherwise the operation is not allowed
}

# Disconnect to the server
Util::disconnect();
