#!/usr/bin/perl -w
#
# Copyright (c) 2007 VMware, Inc.  All rights reserved.


use strict;
use warnings;

use lib "/usr/lib/vmware-vcli/apps/";

use VMware::VIRuntime;
use AppUtil::VMUtil;
use AppUtil::HostUtil;

$Util::script_version = "1.0";

my $codeRetour = 0;

my %opts = (
   'vmname' => {
      type => "=s",
      help => "The name of the virtual machine",
      required => 0,
   },
   'datacenter' => {
      type     => "=s",
      variable => "datacenter",
      help     => "Name of the datacenter",
      required => 0,
   },
   'pool'  => {
      type     => "=s",
      variable => "pool",
      help     => "Name of the resource pool",
      required => 0,
   },
   'hostIP' => {
      type => "=s",
      help => "The IP of the ESX",
      required => 1,
   },
   'host' => {
      type      => "=s",
      variable  => "host",
      help      => "Name of the host" ,
      required => 0,
   },
   'critical' => {
      type     => "=i",
      variable => "critical",
      help     => "lower critical limit (%)",
      required => 1,
   },
   'warning' => {
      type     => "=i",
      variable => "warning",
      help     => "lower warning limit (%)",
      required => 1,
   },
   'dataType' => {
      type     => "=s",
      variable => "dataType",
      help     => "Type de donnees : VMmem, VMcpu, HostMem, HostCpu, Datastore",
      required => 1,
   },
);

Opts::add_options(%opts);
Opts::parse();
Opts::validate(\&validate_dataType);

my $hostIP = Opts::get_option('hostIP');
my $test= Opts::set_option ('url',"https://$hostIP/sdk/webService");

Util::connect();
if ( Opts::get_option('dataType') eq 'VMmem') {
  get_VM_mem_info();
} elsif (Opts::get_option('dataType') eq 'VMcpu' ) {
  get_VM_cpu_info();
} elsif (Opts::get_option('dataType') eq 'HostCpu' ) {
  get_host_cpu_info();
} elsif (Opts::get_option('dataType') eq 'HostMem' ) {
  get_host_mem_info();
} elsif (Opts::get_option('dataType') eq 'Datastore' ) {
  get_datastore_info();
}

Util::disconnect();

exit $codeRetour;

sub get_VM_cpu_info {
  my %filter;
  $filter{'summary.config.vmotionEnabled'} = 'false';
  $filter{'runtime.inMaintenanceMode'} = 'false';
  $filter{'name'} = Opts::get_option ('host');
  my $host_views = HostUtils::get_hosts('HostSystem',
                                     Opts::get_option ('datacenter'),
                                     Opts::get_option ('folder'),
				  );
  if ($host_views) {
    foreach (@$host_views) {
      my $host_view = $_;
      print $host_view->name;  
      my $Hz = $host_view->hardware->cpuInfo->hz; 
      my $vm_views = VMUtils::get_vms ('VirtualMachine',
                                     Opts::get_option ('vmname'),
                                     Opts::get_option ('datacenter'),
                                     Opts::get_option ('folder'),
                                     Opts::get_option ('pool'),
                                     $host_view->name,
				  );
      if ($vm_views) { 
        foreach (@$vm_views) {
          my $vm_view = $_;
	  my $percentCpuUsed = ( $vm_view->summary->quickStats->overallCpuUsage * 100000000 ) / ( $vm_view->summary->config->numCpu * $Hz ); 
          print "  ".$vm_view->config->name." : ";
          printf "%.0f ",$percentCpuUsed; 
          print "%CPU Used"; 
          if ( $percentCpuUsed > Opts::get_option ('critical') ) {
            $codeRetour = 2;
          } elsif ( $percentCpuUsed > Opts::get_option ('warning') && $codeRetour eq '0' ) {
            $codeRetour = 1;
          }
        }
      }
    }
  }
}

sub get_VM_mem_info {
  my $vm_views = VMUtils::get_vms ('VirtualMachine',
                                     Opts::get_option ('vmname'),
                                     Opts::get_option ('datacenter'),
                                     Opts::get_option ('folder'),
                                     Opts::get_option ('pool'),
                                     Opts::get_option ('host'),
                                  );
  my $PercentMemoryUsed;
  $codeRetour=0;
  foreach (@$vm_views) {
    my $vm_view = $_;
    my $configuredMemory = $vm_view->summary->config->memorySizeMB;
    my $usedMemory = $vm_view->summary->quickStats->guestMemoryUsage;
    $PercentMemoryUsed = $usedMemory * 100 /$configuredMemory;

    print "  ".$_->name." : ";
    printf "%.0f ",$PercentMemoryUsed;
    print "%Mem Used";
    if ( $PercentMemoryUsed > Opts::get_option ('critical') ) {
      $codeRetour = 2;
    } elsif ( $PercentMemoryUsed > Opts::get_option ('warning') && $codeRetour eq '0' ) {
      $codeRetour = 1;
    }
  }
}

sub get_host_cpu_info {
  my %filter;
  $filter{'summary.config.vmotionEnabled'} = 'false';
  $filter{'runtime.inMaintenanceMode'} = 'false';
  $filter{'name'} = Opts::get_option ('host');
  my $host_views = HostUtils::get_hosts('HostSystem',
                                     Opts::get_option ('datacenter'),
                                     Opts::get_option ('folder'),
                                  );
  if ($host_views) {
    foreach (@$host_views) {
      my $host_view = $_;
      print $host_view->name." : ";
      my $percentCpuUsed = $host_view->summary->quickStats->overallCpuUsage * 100000000/ ($host_view->hardware->cpuInfo->hz * $host_view->hardware->cpuInfo->numCpuCores);
      printf "%.0f ",$percentCpuUsed;
      print "%CPU Used  ";
      if ( $percentCpuUsed > Opts::get_option ('critical') ) {
        $codeRetour = 2;
      } elsif ( $percentCpuUsed > Opts::get_option ('warning') && $codeRetour eq '0' ) {
        $codeRetour = 1;
      }
    }
  }
}

sub get_host_mem_info {
  my %filter;
  $filter{'summary.config.vmotionEnabled'} = 'false';
  $filter{'runtime.inMaintenanceMode'} = 'false';
  $filter{'name'} = Opts::get_option ('host');
  my $host_views = HostUtils::get_hosts('HostSystem',
                                     Opts::get_option ('datacenter'),
                                     Opts::get_option ('folder'),
                                  );
  if ($host_views) {
    foreach (@$host_views) {
      my $host_view = $_;
      print $host_view->name." : ";
      my $PercentMemoryUsed = $host_view->summary->quickStats->overallMemoryUsage * 1024 * 1024 * 100 / $host_view->hardware->memorySize;
      printf "%.0f ",$PercentMemoryUsed;
      print "%Mem Used";
      if ( $PercentMemoryUsed > Opts::get_option ('critical') ) {
        $codeRetour = 2;
      } elsif ( $PercentMemoryUsed > Opts::get_option ('warning') && $codeRetour eq '0' ) {
        $codeRetour = 1;
      }
    }
  }
}

sub get_datastore_info {
  my $ds_name = "";
  if (defined Opts::get_option('name')) {
    $ds_name = Opts::get_option('name');
  }
  my $dc =  Vim::find_entity_views(view_type => 'Datacenter');
  my @ds_array = ();
  foreach(@$dc) {
    if (defined $_->datastore) {
      @ds_array = (@ds_array, @{$_->datastore});
    }
  }
  my $datastores = Vim::get_views(mo_ref_array => \@ds_array);
  foreach(@$datastores) {
    print "  ".$_->summary->name." : ";
    my $percentUsed = 100 - ($_->summary->freeSpace * 100 / $_->summary->capacity);
    printf "%.0f ",$percentUsed;
    print "% Used";
    if ( $percentUsed > Opts::get_option ('critical') ) {
      $codeRetour = 2;
    } elsif ( $percentUsed > Opts::get_option ('warning') && $codeRetour eq '0' ) {
      $codeRetour = 1;
    }
  } 
}

sub validate_dataType {
  my @validDataType = ("VMmem", "VMcpu", "HostMem", "HostCpu", "Datastore");
  my $isvalid = 0;
  foreach (@validDataType) {
    if ($_ eq Opts::get_option ('dataType')) {
      $isvalid = 1;
    }
  }
  if ( Opts::get_option ('warning') > Opts::get_option ('critical') ) {
    $isvalid = 0;
    print "critical should be grather than warning\n";
  }
  return $isvalid;
}
