#! /usr/bin/env perl

use strict;
use warnings;
use Data::Dumper;


my $target = shift;
die "Syntax: $0 target virtual [virtual...]\n" unless $target;

my @toProcess = @ARGV;

my $hypervisor = 'virsh'; $hypervisor = 'xl' unless `which $hypervisor`;

die "Could not determine hypervisor\n" unless `which $hypervisor`;


sub checkConnection {
   my ($hypervisor,$target) = @_;
   if ( $hypervisor eq 'virsh' ) {
      die "Could not make a connection to $target\n" unless `virsh -c qemu+ssh://$target/system list`;
   } else {
      die "I don't know how to migrate Xen\n";
   }
}

sub trim {
   my $string = shift;
   $string =~ s/^\s+|\s+$//;
   return $string;
}

# get the name and ID of all virtuals running on this machine
sub getRunningVirtuals {
   my $hypervisor = shift;
   my %virtuals;
   if ( $hypervisor eq 'virsh' ) {
      my @output = `virsh list`;
      my @headers = split( '\s+', lc( trim( $output[0] ) ) );
#      die join( "\n", @headers ) . "\n"; 
      for (my $line = 1; $line < @output; $line++ ) {
         next if $output[$line] =~ m/^[^\s]*$/; # skip line of all dashes or empty
         my %temp;
         @temp{@headers} = split( '\s+', trim( $output[$line] ) );
         $virtuals{$temp{'name'}} = $temp{'id'};
      }
   } else {
      die "I don't know how to get a list of virtuals for $hypervisor\n";
   }
   return \%virtuals;
}


sub checkVirtual {
   my ($runningDomains, $domain ) = @_;
   # if they gave us a valid name, just return it
   return $domain if $runningDomains->{$domain};
   if ( $domain =~ m/^\d+$/ ) { # they passed a number, is it an ID?
      foreach my $this ( keys %$runningDomains ) {
         # if it is the id, return the name
         return $this if ( $runningDomains->{$this} == $domain );
      }
   }
   die "The domain, $domain, was not found on this machine\n";
}

&checkConnection( $hypervisor,$target );
my $running = &getRunningVirtuals( $hypervisor );

if ( $toProcess[0] eq 'ALL' ) {
   print "Warning, you are moving everything! Type 'yes' to continue ";
   my $yesno = <STDIN>;
   chomp $yesno;
   die unless ( lc $yesno eq 'yes' );
   @toProcess = keys %$running;
}


while ( my $domain = shift @toProcess ) {
   my $domainName = &checkVirtual( $running, $domain );
   print "\n==Migrating $domainName to $target\n";
   print "\tvirsh migrate --live --persistent --verbose  $domain qemu+ssh://$target/system\n";
   `virsh migrate --live --persistent --verbose  $domain qemu+ssh://$target/system`
}
