#!/usr/local/bin/perl -w
###########################################
# cpan-smoke - VM CPAN module smoker
# Mike Schilli, 2011 (m@perlmeister.com)
###########################################
use strict;
use Sysadm::Install qw(:all);
use Proc::Simple;
use Net::Ping;
use Log::Log4perl qw(:easy);

my( $tarball) = @ARGV;

die "usage: $0 tarball" if 
  !defined $tarball;

Log::Log4perl->easy_init($ERROR);

my $vbm    = "VBoxManage";
my $vbh    = "VBoxHeadless";
my $vm     = "Ubuntu 10.04";
my $ippath = 
  "/VirtualBox/GuestInfo/Net/0/V4/IP";
my $snap   = "CPAN Smoke";

  # in case it's up in foreground
tap $vbm, "controlvm", $vm, "poweroff";
tap $vbm, "snapshot", 
    $vm, "restore", $snap;

my $proc = Proc::Simple->new();
$proc->start("$vbh --startvm '$vm'");
END {
    $proc->kill();
}

INFO "Waiting for VM to come up";

while( !$proc->poll() ) {
    DEBUG "Waiting for VM process";
    sleep 1;
}

my $ip;

while( !defined($ip = ip()) ) {
    DEBUG "Waiting for IP";
    sleep 1;
}

my $ping = Net::Ping->new();
while( !$ping->ping($ip) ) {
    DEBUG "Waiting for Ping";
    sleep 1;
}

INFO "VM is up: $ip";

tap "scp", $tarball, "$ip:/tmp/$tarball";
sysrun "ssh", $ip, 
  qq{eval \$(/usr/bin/perl -Mlocal::lib); 
     cpanm /tmp/$tarball};

tap $vbm, "controlvm", $vm, "poweroff";
tap $vbm, "snapshot", 
    $vm, "restore", $snap;

###########################################
sub ip {
###########################################
  my($stdout) = tap $vbm, "guestproperty", 
                    "get", $vm, $ippath;

  if( $stdout =~ /Value: (.*)/ ) {
    return $1;
  }

  return undef;
}
