#!/usr/bin/perl
=head1 NAME

vmm - Manage VMware virtual machines

=head1 SYNOPSIS

	vmm <command> [options]

=over
	
=item B<Global syntax:>

	vmm <command> [-f] [-v+] [-w seconds] [@profile]

=item B<Command specific syntax:>

	vmm clone [-o pool] [-c count] [-a datastore...] <source vm> <new vm name>
	vmm df [-h] [datastore...]
	vmm host [maintenance|restore|restart|shutdown|disconnect|reconnect] <hosts...>
	vmm list [-d col1,col2... | perl string] [-t title] [vms|datastores|hosts|pool] [patterns...]
	vmm migrate [-p low|normal|high] [-o pool] <vms...> <host>
	vmm move [-o pool] <vms...> <datastore>
	vmm setpool <low|normal|high> <cpu|mem|all> <pools...>
	vmm show [vm|datastore|host|pool] [items...]
	vmm snapshot [-t title] <vms...>
	vmm state <on|off|suspend|reboot|shutdown|restart|standby> <vms...>
	vmm version

=back

=head1 COMMANDS

=over 8

=item B<clone>

Clone a given VM to another VM name.
If -c is specified multiple copies are made. Each VM name will be incremented in the usual Perlish way. e.g.: DB1, DB2, DB3 etc.

If -a is unspcified the datastore of the source VM is copied as the new clones datastore.
If -a is specified the data store will be set during cloning. If -a contains a comma denoted list the datastores will be alternated during cloning. e.g. -a 1,2 copies to datastore 1 then 2 then starts again at 1. Patterns of repeating datastores can be specified - e.g. '-a 1,2,3,2,1'.

=item B<df>

Display disk usage information about datastores.
If a list of matches is provided, the data store list is filtered for those items.

=item B<list>

Display a list of the given items matching a pattern.

Possible lists include (selection can be plural or singular):
* vms (default if unspecified)
* datastores
* hosts
* pools

If '-d' is specified without any containing '$' marks the string is evaluated as a CSV with each line extracting the requisite information that would be shown with the 'show' command. See the EXAMPLES section for further information.

If '-d' is specified and contains a '$' it is evaluated as a perl expression with $_ being set to the currently active item.

If '-t' is spcified the titles header for the table is set.

=item B<migrate>

Migrate a given list of VMs to another host.

=item B<move>

Move a given list of VMs to another datastore.

=item B<setpool>

Set the share level on the given resource pools.

=item B<show>

Show information about a given object. If no specific object type is specified 'vm' is assumed.
If no specific matching pattern is specified all objects of that type are listed.

=item B<snapshot>

Take a snapshot of the matching VM's.
If '-t' is specified, it is used as the title of the snapshot. Otherwise the current time is used.

=item B<state>

Set the state of a list of VMs.

This can be any of the following choices:
* on - Power up the specified VMs
* off - Power down the specified VMs. This is a hard power state so data loss could occur.
* suspend - Power the machine into standby mode. This is a hard power state which does not rely on VMware tools.
* restart - Hard power cycle the VMs. Like 'off' this is a forced power state so data loss could occur.
* shutdown - Try shutting down the machine via VMware tools.
* standby - Try to put the machine into the soft standby state.
* reboot - Try shutting down the machine via VMware tools.

=item B<version>

Display various version informaiton about the connected vServer and local API.
This command is the default if no actual command is specified (i.e. just running 'vmm' with nothing else specified).

=back

=head1 OPTIONS

=over 8

=item B<[@profile]>

=over

=item B<Used during:>
All operations

=item B<Default:>
First specified profile in config

=item B<Type:>
Profile name or URL

=back

Specifies which profile to use when addressing the vServer.
This can be an entry within the config file or the URL (with optional login details) e.g.

	vmm version @cluster1
	vmm version @cluster2
	vmm version @https://cluster1.acme.edu
	vmm version @https://username@cluster1.acme.edu
	vmm version @https://username:password@cluster1.acme.edu

Examples 1 and two assume 'custer1' and 'customer2' have been defined in the examples file (see EXAMPLES). The further examples specify the connection information on the command line.
Specifying the password from the command line is exceptionally silly and should be avoided.

If username and/or password is omitted (such as in examples 3 and 4 above) they will be prompted for when vmm is run.

=item B<-c>

=over

=item B<Used during:>
migrate

=item B<Default:>
1

=item B<Type:>
Number

=back

Specifies how many VMs should be created during a clone operation.
The name of the target VM is incremented in the usual Perlish way.
e.g.

DBS1, DBS2, DBS3... DBS10
DB00, DB01, DB02... DB99
DBAA, DBAB, DBAC,,, DBZZ

=item B<--display [col1,col2...]>

=item B<-d [col1,col2...]>

=over

=item B<Used during:>
list

=item B<Default:>
Name

=item B<Type:>

Command seperated list of columns to display in tabular output when using the 'list' command.
See also: -s to specify the seperation character to use between the columns.

=back

Specify a data store for operations that require it.

=item B<--datastore [datastore]>

=item B<--ds [datastore]>

=item B<-a [datastore]>

=over

=item B<Used during:>
migrate

=item B<Default:>
Same as source VM

=item B<Type:>
Datastore name

=back

Specify a data store for operations that require it.

=item B<-f>

=over

=item B<Used during:>
All operations

=item B<Default:>
off

=item B<Type:>
Switch

=back

Force continue if an error occurs.
Normaly if an error occurs vmm will stop processing any further VMs specified on the command line.
If this flag is enabled vmm will instead continue operation as if no error occured.

=item B<--human>

=item B<-h>

=over

=item B<Used during:>
df

=item B<Default:>
off

=item B<Type:>
Switch

=back

Display the numbers of the 'df' command in a human readable format.

=item B<--dryrun>

=item B<-n>

=over

=item B<Used during:>
All operations

=item B<Default:>
off

=item B<Type:>
Switch

=back

Dry run mode.
When enabled vmm will continue as normal but no actual call to the VMware VServer is made.

=item B<--pool [pool]>

=item B<-o [pool]>

=over

=item B<Used during:>
clone, migrate, move

=item B<Default:>
Same as the source VM

=item B<Type:>
Pool name

=back

Specifies the alternate pool name to use when migrating or cloning machines. If unspecified the source VM's pool is used instead.

=item B<--priority [priority]>

=item B<-p [priority]>

=over

=item B<Used during:>
migrate

=item B<Default:>
low

=item B<Type:>
Choice of: low, normal, high

=back

Specifies the priority when migrating VMs.

=item B<--seperator [character]>

=item B<-s [character]>

=over

=item B<Used during:>
list

=item B<Default:>
\t (tab)

=item B<Type:>
String

=back

Specifies the string to display between columns when outputing a list.

=item B<--title [title]>

=item B<-t [title]>

=over

=item B<Used during:>
list, snapshot

=item B<Default:>
The Unix EPOC (for VMs)

=item B<Type:>
String

=back

The title of the snapshot to create or the title row of the list table.

=item B<-v>

=item B<--verbose>

=over

=item B<Used during:>
All operations

=item B<Default:>
0

=item B<Type:>
Accumulating switch

=back

Be more verbose when outputting information to STDERR.
Specify multiple times to increase verbosity.

=item B<-w [seconds]>

=item B<-wait [seconds]>

=over

=item B<Used during:>
clone, host, migrate, setpool, state

=item B<Default:>
0

=item B<Type:>
Number of seconds

=back

Force a wait for the specified number of seconds between operations.

=back

=head1 DESCRIPTION

A command line tool for the manipulation of VMware Virtual Machines (VM).

=head1 EXAMPLES

=over

=item B<vmm clone VM01 VM02>

Clone VM01 to VM02.
Since neither the datasource (-d) or pool (-o) is specified these details are copied from VM01.

=item B<vmm clone DB00 DB01 -c 30>

Clone DB01 to DB02 creating 30 copies. This will actually make the machines DB01 to DB30.
Since neither the datasource (-d) or pool (-o) is specified these details are copied from VM01.

=item B<vmm clone DB00 DB01 -c 30 -d SAN1,SAN2 -o Active>

Same as the above example but spread the datastores across SAN1 and SAN2 and move the machine to the 'Active' pool.

=item B<vmm df *2>

Display a datastore usage sheet (similar to the Unix 'df' command) for all datastores ending in '2'.

=item B<vmm host maintenance Moe Homer>

Put the hosts 'Moe' and 'Homer' into maintenance mode (use 'restore' to recover from this).

=item B<vmm list vms>

List all VMs.

=item B<vmm list vms -d name,host,ip>

List all VMs - showing their name, currently allocated host and IP address.

=item B<vmm migrate DBS* Carl>

Migrate all virtual machines matching 'DBS*' to the 'Carl' host.

=item B<vmm migrate DBS* Lenny -w 60 -o Active -p high>

Migrate all virtual machines matching 'DBS*' with high priority to the 'Active' pool on the 'Lenny' host waiting 60 seconds between machine.

=item B<vmm move DB00 DB01 SAN2 @cluster2>

Move VMs DB00 and DB01 to the SAN2 datastore within profile 'cluster2'.

=item B<vmm show host Lisa>

Show information on host 'Lisa'.

=item B<vmm snapshot DB04 DB05 -t 'Todays backup'>

Take a snapshot of VMs 'DB04' and 'DB05' using the title 'Todays backup'

=item B<vmm state on DB00 DB01 -w 30>

Turn DB00 and DB01 on waiting 30 seconds between machines.

=back

=head1 FILES

=over 8

=item B</etc/vmmrc>

VMM config file for all users.

=item B<.vmmrc>

VMM config file for the local user.

=back

=head1 CONFIG

The /etc/vmmrc and .vmmrc files will be processed to determine VMM's configuration, the latter file taking precedence.

The layout of the config file spcifies which profiles to use.

	[GLOBAL]
	rewrite host = s/^(.+?)\./\1/
	verbose = 2
	profile = Cluster1
	dryrun = 0
	human = 1
	seperator = \t
	
	[Cluster1]
	url = https://cluster1.acme.edu
	username = admin
	password = password
	
	[Cluster2]
	url = https://cluster2.acme.edu
	username = administrator
	password = changeme

=over 8

=item B<[GLOBAL]>

The meta global section. Any option specified here will be automatically carried into each profiles config.

In the main example Cluster1 will have a 'verbose' option of 2. Cluster2 will have a 'verbose' option of 1 since it overrides the global setting.

=item B<[profile]>

The name (case-insensitive) of the profile to define.

=item B<url>

The connection URL of the vServer system within the profile

=item B<username> and B<password>

The authentication information when connecting to the vServer.

=item B<dryrun>

Specify a default dry run value. See B<-n> for further information.

=item B<human>

Always output numbers in a human readable format rather than the raw form.

=item B<priority>

Specify a default priority when using any command that is '-p' compatible.

=item B<profile>

Specify the default profile to use if none is explicitally set. If not specified the first found profile in the config file is used.

=item B<rewrite host>

Specify a substitution regular expression to use when correcting host names.
The value given in the above example will remove any trailing DNS name correcting 'host1.a.very.long.dns.com' to 'host1'.

=item B<seperator>

Specify the seperator character used when outputting tabular data with the 'list' command.

=item B<verbose>

Specify a default verbosity level. See B<-v> for further information.

=back

=head1 BUGS

Quite probably.

Please report to https://github.com/hash-bang/VMM when found.

=head1 AUTHOR

Matt Carter <m@ttcarter.com>

=cut

# Header {{{
use Config::IniFiles;
use IO::Handle;
use Getopt::Long;
use Number::Bytes::Human qw/format_bytes/;
use Term::ReadKey;
use Text::Glob qw/match_glob glob_to_regex/;
use VMware::VIRuntime;
Getopt::Long::Configure('bundling', 'ignorecase_always', 'pass_through');
STDERR->autoflush(1); # } Flush the output DIRECTLY to the output buffer without caching
STDOUT->autoflush(1); # }

use Data::Dumper; # FIXME: Debugging modules
# }}} Header

# Functions {{{
# Flow control {{{
sub fatal {
	# Print an error message and fatally die
	print STDERR @_, "\n";
	exit 1;
}

sub say {
	# Print a message to STDERR based on the verbosity level
	our $verbose;
	my $verbosity = shift;
	print STDERR @_, "\n";
}

sub pause {
	# Wait a number of seconds (specified by the -w [seconds]) between VM operations
	# This function purposely ignores the first vm (thus not bothering to wait for the last vm to finish)
	our $wait;
	if ($wait > 0) {
		say(0, "Waiting $wait seconds...");
		sleep($wait);
	}
}

sub error {
	# FIXME: This function is pretty basic and needs a user-friendlyness upgrade
	my $action = shift;
	my $subject = shift;
	if (ref($@) eq 'SoapFault') {
		say(0, "An error occured: " . $@->detail);
	} else {
		say(0, "General fault!");
	}
}
# }}} Flow control

# Filters {{{
sub list {
	my $type = shift;
	my @out;
	return grep {
		if ($type eq 'VirtualMachine' and !$_->resourcePool) {
			undef;
		} else {
			$_ = $_->name;
		}
	} @{Vim::find_entity_views (
		view_type => $type,
		begin_entity => Vim::get_service_content()->rootFolder,
		filter => {},
	)};
	return @out;
}

sub multiglob {
	# Perform multiple greps and return all matching list items
	# e.g. multiglob(qw/apple pear orange tomatoe carrot/, qw/*pp* *ar *zz/) = qw/apple pear/
	# If the list of matches is empty, all are returned
	my ($list, $globs) = @_;
	return @$list unless @$globs;
	@globs = map { $_ = glob_to_regex($_) } @$globs;

	#print "LIST [" . Dumper($list) . "]";
	#print "GLOBS [" . Dumper($globs) . "]";

	return grep {
		my $found = 0;
		foreach $glob (@$globs) {
			if ($_ =~ $glob) {
				$found = 1;
				last;
			}
		}
		$found;
	} @$list;
}
# }}} Filters

# Info grabbers {{{
sub translate {
	my $type = shift;
	$type =~ s/s$//; # Correct plurals -> singular
	my %translate = qw/
		vm		VirtualMachine
		host		HostSystem
		datastore	Datastore
		d		Datastore
		pool		ResourcePool
	/;
	return $translate{$type} ? $translate{$type} : undef;

}

sub getview {
	# Return a VMware view object from its type and reference
	# This function also supports the meta type 'Mor' which looks up the view by the managed object reference
	my $type = shift; # HostSystem, VirtualMachine, ResourcePool
	my $ref = shift;
	if ($type eq 'Mor') {
		return Vim::get_view(
			mo_ref => $ref,
		);
	} else {
		return Vim::find_entity_view(
			view_type => $type,
			filter => { name => $ref },
		);
	}
}

sub getinfo {
	# Generic function to return information from one of the below get<type>info functions
	my $type = shift;
	my $name = shift;
	if ($type eq 'VirtualMachine') {
		return getvminfo($name);
	} elsif ($type eq 'Datastore') {
		return getdsinfo($name);
	} elsif ($type eq 'HostSystem') {
		return gethostinfo($name);
	} elsif ($type eq 'ResourcePool') {
		return getpoolinfo($name);
	}
}

sub getvminfo {
	my $vm = shift;
	my $view = getview('VirtualMachine', $vm) or fatal("Unknown VM: '$vm'");
	my %info = (
		name => $view->name,
		template => $view->summary->config->template eq '0' ? 'none' : $view->summary->config->template,
		os => $view->summary->guest->guestFullName,
		datastore => Vim::get_view(mo_ref => ${$view->datastore}[0])->name,
		pool => Vim::get_view(mo_ref => $view->resourcePool)->name,
		booted => $view->runtime->bootTime,
		alloccpu => $view->summary->config->numCpu,
		allocmem => $view->summary->config->memorySizeMB,
		allocdisks => $view->summary->config->numVirtualDisks,
		maxcpu => $view->runtime->maxCpuUsage,
		maxmem => $view->runtime->maxMemoryUsage,
		host => Vim::get_view(mo_ref => $view->runtime->host)->name,
		state => $view->runtime->powerState->val eq 'poweredOn' ? 'on' : 'off',
		tools => $view->guest->toolsStatus->val eq 'toolsOk' ? 'yes' : 'no',
		folder => $view->parent->name,
		ip => 'UNKNOWN',
		mac => 'UNKNOWN',
	);

	if ($view->guest->disk) {
		foreach (@{$view->guest->disk}) {
			my $no;
			$info{'disk_' . $no++} = $_->diskPath . ' ' . $_->capacity . ' ' . $_->freeSpace;
		}
	}

	if ($view->guest->net) {
		foreach $net (@{$view->guest->net}) {
			my $no;
			$info{'net_' . $no++} = $net->network . ' ' . $net->macAddress . ' ' . join(',', @{$net->ipAddress});
			$info{ip} = join(',', @{$net->ipAddress}) if $info{ip} eq 'UNKNOWN'; # Lazy accessor for 'ip'
			$info{mac} = $net->macAddress if $info{mac} eq 'UNKNOWN'; # Lazy accessor for 'mac'
		}
	}
	return %info;
}

sub getdsinfo {
	my $ds = shift;
	our $human;
	my $view = getview('Datastore', $ds) or fatal("Unknown datastore: '$ds'");
	my %info = (
		name => $view->name,
		size => ($human ? format_bytes($view->info->vmfs->capacity) : $view->info->vmfs->capacity),
		used => ($human ? format_bytes($view->info->vmfs->capacity - $view->info->freeSpace) : $view->info->vmfs->capacity - $view->info->freeSpace),
		free => ($human ? format_bytes($view->info->freeSpace) : $view->info->freeSpace),
		percent => sprintf('%d', (($view->info->vmfs->capacity - $view->info->freeSpace) / $view->info->vmfs->capacity * 100)),
	);
	return %info;
}

sub gethostinfo {
	my $host = shift;
	my $view = getview('HostSystem', $host) or fatal("Unknown host: '$ds'");
	my %info = (
		name => $view->name,
		cpuuse => $view->summary->quickStats->overallCpuUsage,
		memuse => $view->summary->quickStats->overallMemoryUsage,
		mem => $view->hardware->memorySize,
		cpu => $view->hardware->cpuInfo->hz,
	);

	if ($view->datastore) {
		foreach $dsmor (@{$view->datastore}) {
			my $no;
			my $dsref = getview('Mor', $dsmor);
			$info{'datastore_' . $no++} = $dsref->name;
		}
	}
	return %info;
}

sub getpoolinfo {
	my $pool = shift;
	my $view = getview('ResourcePool', $pool) or fatal("Unknown pool: '$pool'");
	my %info = (
		name => $view->name,
		maxmem => $view->runtime->memory->maxUsage,
		maxcpu => $view->runtime->cpu->maxUsage,
		mem => $view->runtime->memory->overallUsage,
		cpu => $view->runtime->cpu->overallUsage,
		memshare => $view->config->memoryAllocation->shares->level->val,
		cpushare => $view->config->cpuAllocation->shares->level->val,
	);
	return %info;
}
# }}} Info grabbers
# }}} Functions

# Config loading {{{
my $cfgfile;
if (-e "/etc/vmmrc") {
	$cfgfile = "/etc/vmmrc";
} elsif (-e "$ENV{HOME}/.vmmrc") {
	$cfgfile = "$ENV{HOME}/.vmmrc";
} else {
	say(1, "No VMMRC file could be found at either /etc/vmmrc or \$HOME/.vmmrc");
}

our $verbose = 0;
my $cfg = Config::IniFiles->new(
	-file => ($cfgfile ? $cfgfile : \*DATA), # Read defaults from __DATA__ section if we cant find a default file.
	-default => 'global',
	-fallback => 'global',
	-nocase => 1,
	-allowempty => 1,
	-handle_trailing_comment => 1,
);


my $profile; # The active profile to use
@ARGV = grep { # Scan for '@profile' strings in @ARGV
	if (/^@(.+)$/) {
		fatal("Only one profile may be set per invocation. Profile was originally '$profile' when you tried to override with '$_'") if $profile;
		if (my($cproto, $clogin, $curl) = (m/^\@(https?):\/\/(?:(.*?)@)?(.*)$/)) { # User is specifying user:pass@url, user@url or url
			my($cuser, $cpass) = ($clogin,undef) unless (($cuser, $cpass) = ($clogin =~ m/^(.*?):(.*)$/));
			say(2, "Using custom URL: $curl");
			$cfg->newval('CUSTOM', 'url', "$cproto://$curl");
			$cfg->newval('CUSTOM', 'username', $cuser) if $cuser;
			$cfg->newval('CUSTOM', 'password', $cpass) if $cpass;
			$profile = 'CUSTOM';
		} else { # Standard profile alias
			$profile = $1;
		}
		undef;
	} else {
		$_;
	}
} @ARGV;

$verbose = $cfg->val('global', 'verbose', 0); # Early import from global so 'say' works correctly in the following profile options
if ($profile) { # User wants to select a specific profile
	fatal("Profile not valid: $profile") unless $cfg->exists($profile, 'url');
	say(2, "Using user set profile '$profile'");
} elsif ($cfg->exists('global', 'profile')) { # Default profile option set in config
	$profile = $cfg->val('global', 'profile');
	say(2, "Using config file default profile '$profile'");
} elsif ($cfg->val('global', 'profile')) { # Config file specifies default fallback profile
	$profile = $cfg->val('global', 'profile', $profile);
} else { # Use first section found that isn't 'global'
	$profile = [grep { $_ ne 'global' } $cfg->Sections]->[0];
	say(2, "Using first found profile '$profile'");
}

fatal("No vServer URL specified for profile $profile") unless $cfg->exists($profile, 'url');
unless ($cfg->val($profile, 'username')) {
	print "Username: ";
	my $cuser = ReadLine(0);
	chomp($cuser);
	$cfg->newval($profile, 'username', $cuser);
}
unless ($cfg->val($profile, 'password')) {
	print "Password: ";
	ReadMode('noecho');
	my $cpass = ReadLine(0);
	chomp($cpass);
	print "\n";
	$cfg->newval($profile, 'password', $cpass);
}

# Import various options from the config file. These can be overriden in the GetOptions call below.
$verbose = $cfg->val($profile, 'verbose', 0); # Late import which overrides the 'global/verbose' setting now we know what profile to use
our $cycleno = 0; # Offset of the object we are operating on
our $dryrun = $cfg->val($profile, 'dryrun', 0);
our $wait = $cfg->val($profile, 'wait', 0);
our $human = $cfg->val($profile, 'human', '0');
my $priority = $cfg->val($profile, 'priority', 'low');
my $seperator = $cfg->val($profile, 'seperator', "\t");
my $title, $display, $pool, $datastore;
my $count = 1;
Opts::set_option('url', $cfg->val($profile, 'url'));
Opts::set_option('username', $cfg->val($profile, 'username'));
Opts::set_option('password', $cfg->val($profile, 'password'));

say(3, "Connecting to " . $cfg->val($profile, 'username') . '@' . $cfg->val($profile, 'url'));
Util::connect();
# }}} Config loading
# Command line options loading {{{
GetOptions(
	# Global options
	'dryrun|n' => \$dryrun,
	'verbose|v+' => \$verbose,
	'wait|w=i' => \$wait,

	# Specific command options
	'count|c=i' => \$count,
	'priority|p=s' => \$priority,
	'pool|o=s' => \$pool,
	'human|h' => \$human,
	'display|d=s' => \$display,
	'seperator|s=s' => \$seperator,
	'title|t=s' => \$title,
	'datastore|ds|a=s' => \$datastore,
);

my $cmd = shift; # Extract what command we should work with
# }}} Command line options loading

if ($cmd eq 'df') { # DF {{{
	# DF is really just a lazy way of configuring the 'list' command
	$cmd = 'list';
	$display = '$_{name}\t$_{size}\t$_{used}\t$_{free}\t$_{percent}%';
	$title = 'Name,Size,Used,Free,%';
	unshift @ARGV, 'datastore';
} # }}}
if ($cmd eq 'clone') { # CLONE {{{
	my $poolref;

	my $source = shift;
	my $target = shift;
	my $sourceref = getview('VirtualMachine', $source) or fatal("Invalid source VM: '$source'");
	my $sourcehost = getview('Mor', $sourceref->runtime->host) or fatal("Invalid host for VM '$source'");
	my @dsrefs;

	if ($pool) { # Requesting a specific pool
		say(2, "Using pool '$pool'");
		$poolref = getview('ResourcePool', $pool) or fatal("Invalid destination pool: $pool");
	} else { # Copy pool from source
		$poolref = $sourceref->resourcePool;
	}
	if ($datastore) { # User is specifying pattern of datastores
		foreach (split(',', $datastore)) {
			say(2, "Loading datastore '$_'");
			my $dsref = getview('Datastore', $_) or fatal("Unknown datastore: '$_'");
			push @dsrefs, $dsref;
		}
	} else { # No DS preferences set - use default clone DS
		push @dsrefs, getview('Mor', $sourceref->datastore->[0]);
	}

	say(1, "Clone source $source (x $count clones, across " . scalar(@dsrefs) ." datastores)");

	while ($cycleno < $count) {
		pause() if $cycleno++;
		while (getview('VirtualMachine', $target)) {
			say(1, "VM '$target' already exists. Trying next slot");
			$target++;
		}

		say(1, "Cloning $source -> $target (clone #$cycleno, DS " . $dsrefs[$dsno]->name . ")");

		eval {
			$sourceref->CloneVM(
				folder => $sourceref->parent,
				name => $target,
				spec => VirtualMachineCloneSpec->new(
					powerOn => 0,
					template => 0,
					location => VirtualMachineRelocateSpec->new(
						datastore => $dsrefs[$dsno],
						host => $sourcehost,
						pool => $poolref,
					)
				)
			) unless $dryrun;
		};
		error('clone', $source, @_) if @_;

		$dsno = 0 if ++$dsno > scalar(@dsrefs)-1; # Move though selected datastores
		$target++;
	}
# }}} CLONE
} elsif ($cmd eq 'list') { # LIST {{{
	my $type = shift || 'vm';
	my $type = translate($type) or fatal("Unknown list type: '$type'");
	my @displaylist;
	my $displaytype = 0; # 0 - Plain list, 1 - CSV list, 2 - Perl string eval
	if ($display =~ /\$/) { # Contains a '$' - assume Perl eval
		$displaytype = 2;
	} elsif ($display) {
		@displaylist = split(',',$display); # Split 'display' CSV option
		print Dumper(@displaylist);
		$displaytype = 1;
	}

	if ($title) { # Output a title
		$title =~ s/,/$seperator/g;
		say(0, $title);
	}

	my @list = multiglob([list($type)], \@ARGV);
	if ($displaytype == 0) { # No custom format - just dump list
		print join "\n", @list;
	} elsif ($displaytype == 1) { # CSV style extract
		unless ($title) {
			foreach $type (@displaylist) { # Print headers
				print "$type$seperator";
			}
		}
		print "\n";
		foreach $item (@list) {
			my %info = getinfo($type, $item) or fatal("Dont know how to retrieve info for type '$type'");
			my $line = '';
			foreach $type (@displaylist) {
				$line .= ($info{$type} ? $info{$type} : 'UNKNOWN') . $seperator;
			}
			$line = substr($line, 0, 0 - length($seperator)); # Stip last $seperator
			print "$line\n";
		}
	} elsif ($displaytype == 2) { # Perl eval
		foreach $name (@list) {
			%_ = getinfo($type, $name) or fatal("Dont know how to retrieve info for type '$type'");
			print eval("return \"$display\"") . "\n";
		}
	}
	print "\n" if @list; # Insert final \n
# }}} LIST
} elsif ($cmd eq 'host') { # HOST {{{
	my $operation = shift;
	fatal('No operation specified. Choose: maintenance, restore, restart, shutdown, disconnect, reconnect') unless $state;
	fatal('Invalid power state specified. Choose: maintenance, restore, restart, shutdown, disconnect, reconnect') unless $state =~ /^maintenance|restore|restart|shutdown|disconnect|reconnect$/;

	my @hosts = multiglob([list('HostSystem')], \@ARGV);
	fatal('No Hosts\'s match the given pattern') unless scalar(@hosts);
	foreach $host (@hosts) {
		pause() if $cycleno++;
		my $hostref = getview('HostSystem', $host) or fatal("Invalid host: $host");
		if ($operation eq 'disconnect') {
			say(1, "Disconnecting host '$host'");
			eval {
				$hostref->DisconnectHost() unless $dryrun;
			}
		} elsif ($operation eq 'reconnect') {
			say(1, "Reconnecting host '$host'");
			eval {
				$hostref->ReconnectHost() unless $dryrun;
			}
		} elsif ($operation eq 'maintenance') {
			say(1, "Entering maintenance mode for host '$host'");
			eval {
				$hostref->EnterMaintenanceMode(timeout => 0) unless $dryrun;
			}
		} elsif ($operation eq 'restore') {
			say(1, "Leaving maintenance mode for host '$host'");
			eval {
				$hostref->ExitMaintenanceMode(timeout => 0) unless $dryrun;
			}
		} elsif ($operation eq 'restart') {
			say(1, "Restarting host '$host'");
			eval {
				$hostref->RebootHost(force => 1) unless $dryrun;
			}
		} elsif ($operation eq 'shutdown') {
			say(1, "Shutdown host '$host'");
			eval {
				$hostref->ShutdownHost(force => 1) unless $dryrun;
			}
		}
		error("host->$operation", $host, @_) if @_;
	}
# }}} HOST
} elsif ($cmd eq 'migrate') { # MIGRATE {{{
	my $poolref, $priorityref;
	fatal("Invalid priority: '$priority'. Choose from: low, normal, high") unless $priority =~ /^low|normal|high$/;
	my $priorityref = VirtualMachineMovePriority->new($priority);

	my $targethost = pop;
	fatal('No destination host specified') unless $targethost;

	$poolref = getview('ResourcePool', $pool) or fatal("Invalid destination pool: $pool") if ($pool);
	my $targethostref = getview('HostSystem', $targethost) or fatal("Invalid destination host: $targethost");

	my @vms = multiglob([list('VirtualMachine')], \@ARGV);
	fatal('No VM\'s match the given pattern') unless scalar(@vms);

	say(2, "Migrating to $targethost with $priority priority");
	foreach $vm (@vms) {
		pause() if $cycleno++;
		say(1, "Migrate $vm -> $targethost");

		my $vmref = getview('VirtualMachine', $vm) or fatal("Invalid VM: $vm");
		my $vmpoolref = $pool ? $poolref : getview('Mor', $vmref->resourcePool); # User either user specified pool or import from source VM

		eval {
			$vmref->MigrateVM(
				host => $targethostref,
				pool => $vmpoolref,
				priority => $priorityref,
				state => $vm->runtime->powerState->val,
			) unless $dryrun;
		};
		error('migrate', $vm, @_) if @_;
	}
# }}} MIGRATE
} elsif ($cmd eq 'move') { # MOVE {{{
	my $poolref, $success;
	my $targetds = pop;
	fatal('No destination datasore specified') unless $targetds;

	my $targetdsref = getview('Datastore', $targetds) or fatal("Invalid destination datastore: $targetds");

	$poolref = getview('ResourcePool', $pool) or fatal("Invalid destination pool: $pool") if ($pool);

	my @vms = multiglob([list('VirtualMachine')], \@ARGV);
	fatal('No VM\'s match the given pattern') unless scalar(@vms);

	say(2, "Moving to datastore '$targetds'");
	foreach $vm (@vms) {
		pause() if $cycleno++ and $success;
		$success = 0;
		say(1, "Move $vm -> $targetds");

		my $vmref = getview('VirtualMachine', $vm) or fatal("Invalid VM: $vm");
		fatal("Invalid virtual machine: $vm") unless $vmref;
		if (getview('Mor', $vmref->datastore->[0])->name eq $targetdsref->name) {
			say(0, "$vm is already located in datastore '$targetds'");
			next;
		}

		my $vmhostref = getview('Mor', $vmref->runtime->host) or fatal("Cannot determine VM host for $vm");
		my $vmpoolref = $pool ? $poolref : getview('Mor', $vmref->resourcePool); # User either user specified pool or import from source VM

		eval {
			$vmref->RelocateVM(spec => VirtualMachineRelocateSpec->new(
				datastore => $targetdsref,
				host => $vmhostref,
				pool => $vmpoolref,
			)) unless $dryrun;
		};
		error('move', $vm, @_) if @_;
		$success = 1;
	}
# }}} MOVE
} elsif ($cmd eq 'state') { # STATE {{{
	my $state = shift;
	fatal('No state specified. Choose: on, off, suspend, reboot, shutdown, restart, standby') unless $state;
	fatal('Invalid power state specified. Choose: on, off, suspend, reboot, shutdown, restart, standby') unless $state =~ /^on|off|reboot|shutdown|suspend|standby|restart$/;

	my @vms = multiglob([list('VirtualMachine')], \@ARGV);
	fatal('No VM\'s match the given pattern') unless scalar(@vms);
	foreach $vm (@vms) {
		pause() if $cycleno++;
		my $vmref = getview('VirtualMachine', $vm) or fatal("Invalid virtual machine: $vm");
		if ($state eq 'on') {
			if ($vmref->runtime->powerState->val eq 'poweredOff') {
				say(1, "Powering on $vm");
				$vmref->PowerOnVM() unless $dryrun;
			} else {
				say(0, "$vm needs to be powered off before it can be turned on (VMware recognises the power state as '" . $vm->runtime->powerState->val . "')!");
			}
		} elsif ($state =~ /^reboot|off|shutdown|suspend|standby|restart$/) {
			if ($vmref->runtime->powerState->val ne 'poweredOn') {
				say(0, "Cannot change VM state to '$state' for '$vm' from the current state '" . $vm->runtime->powerState->val . "'");
			} elsif ($state eq 'reboot') {
				say(1, "Rebooting $vm");
				$vmref->ResetVM() unless $dryrun;
			} elsif ($state eq 'suspend') {
				say(1, "Suspending $vm");
				$vmref->SuspendVM() unless $dryrun;
			} elsif ($state eq 'off') {
				say(1, "Powering off $vm");
				$vmref->PowerOffVM() unless $dryrun;
			} elsif ($state eq 'standby') {
				say(1, "Standby $vm");
				$vmref->StandbyGuest() unless $dryrun;
			} elsif ($state eq 'shutdown') {
				say(1, "Shutting down $vm");
				$vmref->ShutdownGuest() unless $dryrun;
			} elsif ($state eq 'restart') {
				say(1, "Restarting $vm");
				$vmref->RebootGuest() unless $dryrun;
			}
		}
	}
# }}} STATE
} elsif ($cmd eq 'setpool') { # SETPOOL {{{
	my $level = shift;
	fatal('You must specify a level to set. Choose from: low, normal, high') unless $level;
	fatal('Invalid level. Choose from: low, normal, high') unless $level =~ /^low|normal|high$/;
	my $item = shift;
	fatal('You must specify what item to set. Choose from: cpu, mem, all') unless $item;
	fatal('Invalid item selection. Choose from: cpu, mem, all') unless $item =~ /^cpu|mem|all$/;

	my @pools = multiglob([list('ResourcePool')], \@ARGV);
	fatal('No pools match the given pattern') unless scalar(@pools);
	foreach $pool (@pools) {
		pause() if $cycleno++;
		my $poolref = getview('ResourcePool', $pool);
		fatal("Invalid resource pool: $pool") unless $poolref;

		my $newshare = SharesInfo->new(shares => 0, level => SharesLevel->new($level));
		my $cpualloc, $memalloc;
		if ($item eq 'cpu') { # Set CPU, import RAM
			$cpualloc = ResourceAllocationInfo->new(shares=>$newshare);
			$memalloc = $poolref->config->memoryAllocation;
		} elsif ($item eq 'mem') { # Set RAM, import CPU
			$cpualloc = $poolref->config->cpuAllocation;
			$memalloc = ResourceAllocationInfo->new(shares=>$newshare);
		} else { # Set both to the same value
			$cpualloc = ResourceAllocationInfo->new(shares=>$newshare);
			$memalloc = ResourceAllocationInfo->new(shares=>$newshare);
		}
		my $config = ResourceConfigSpec->new(cpuAllocation=>$cpualloc, memoryAllocation=>$memalloc);
		$poolref->UpdateConfig(config => $config) unless $dryrun;
	}
# }}} SETPOOL
} elsif ($cmd eq 'show') { # SHOW {{{
	my $rawtype = $type = shift;
	unless ($type = translate($type)) { # First arg is not a recognised type - assume the user is just listing VMs
		unshift @ARGV, $rawtype; # Add back to pattern list
		$type = 'VirtualMachine';
		say(1, "No specific type requested. Assuming: 'vm'");
	}

	my @items = multiglob([list($type)], \@ARGV);
	foreach $item (@items) {
		my %info = getinfo($type, $item);
		print "$key = $val\n" while (($key, $val) = each %info);
		print "\n";
	}
# }}} SHOW
} elsif ($cmd eq 'snapshot') { # SNAPSHOT {{{
	my $success;
	my @vms = multiglob([list('VirtualMachine')], \@ARGV);
	fatal('No VM\'s match the given pattern') unless scalar(@vms);
	$title = $title || time;
	foreach $vm (@vms) {
		say(1, "Snapshot '$vm'");
		pause() if $cycleno++ and $success;
		$success = 0;
		my $vmref = getview('VirtualMachine', $vm) or fatal("Invalid virtual machine: $vm");
		eval {
			$vmref->CreateSnapshot(
				name => $title,
				description => 'VMM created snapshot',
				memory => 0,
				quiesce => 1,
			) unless $dryrun;
		};
		if (@_) {
			error('snapshot', $vm, @_);
		} else {
			$success = 1;
		}
	}
# }}} SNAPSHOT
} elsif ($cmd eq 'version' or !$cmd) { # VERSION {{{
	my $service = Vim::get_service_content();
	print "vServer name: " . $service->about->fullName, "\n";
	print "vServer OS: " . $service->about->osType . "\n";
	print "API version: " . $service->about->apiVersion . " (build " . $service->about->build, ")\n";
	print "Perl toolkit version: " . VMware::VIRuntime->VERSION . "\n";
# }}} VERSION
} else { # OTHER {{{
	fatal("Unknown command: '$cmd'");
# }}}
}

# Default config file
__DATA__
[GLOBAL]
verbose = 1
dryrun = 0
