#!/usr/bin/env perl

use strict;
use warnings;

use CondorTest;
use Check::SimpleJob;

#
# How to use this test:
#
# (1) You must be root.
# (2) The binaries under test must come before any other HTCondor binary
#     in your PATH.
# (3) CONDOR_CONFIG must point to a configuration pointing to the binaries
#     in step (2).
# NB: Steps (2) and (3) may be most-easily accomplished, after the
#     'make install' step, by using condor_install (make a personal condor)
#     and sourcing the resulting 'condor.sh'.
# (4) Download and extract the test VM image and input file:
#     https://parrot.cs.wisc.edu/externals/kvm-test.tar.gz
# (5) This will create the 'kvm-test' directory.  From that directory,
#     run a command something like the following:
#     PERL5LIB=..;../../condor_scripts ../job_kvm_basic.run
# (6) Wait a while.
# (7) This test, succeed or fail, WILL leave behind a personal HTCondor
#     started by root.  You probably want to kill it.
#

my $testName = "job_kvm_basic";

# Turn on KVM.
#testreq: personal
my $config = <<CONDOR_TESTREQ_CONFIG;
    VM_TYPE = kvm
    VM_MEMORY = 256
    VM_NETWORKING = FALSE
    DAEMON_LIST = MASTER STARTD COLLECTOR NEGOTIATOR SCHEDD
CONDOR_TESTREQ_CONFIG
#endtestreq

my $submitFragment = '
    vm_type         = kvm
    vm_memory       = 128
    vm_networking   = false
    vm_no_output_vm = false
    vm_disk         = condor-test.qcow2:hda:w:qcow2,input-disk.raw:hdb:w:raw

    transfer_input_files    = condor-test.qcow2,input-disk.raw
    transfer_output_files   = input-disk.raw
    transfer_output_remaps  = "input-disk.raw = output-disk.raw"
    ';

my $onSuccess = sub {
    my $outputDisk = undef;
    if( open( $outputDisk, '<', 'output-disk.raw' ) ) {
        my $firstLine = <$outputDisk>;
        close( $outputDisk );
        if( $firstLine eq "TEST SUCCESSFUL\n" ) {
            CondorTest::RegisterResult( 1, @_ );
            return;
        }
    }
    CondorTest::RegisterResult( 0, @_ );
};

#
# We can't submit jobs as root.
#
my $originalGID = $);
my $originalUID = $>;
my( $login, $password, $uid, $gid ) = getpwnam( 'condor' );
$) = $gid;
$> = $uid;
# This prevents us from returning to our normal UID, but fork()ing
# will probably break things...
$( = $gid;
$< = $uid;

SimpleJob::RunCheck(
    test_name               => $testName,
    runthis                 => 'KVM Test',
    universe                => 'vm',
    should_transfer_files   => 'TRUE',
    when_to_transfer_output => 'ON_EXIT',
    append_submit_commands  => $submitFragment,
    on_success              => $onSuccess,
);

#
# Return back to being root so we can terminate the personal condor.
#
# NB: This doesn't actually work; see above.
#
$) = $originalGID;
$> = $originalUID;

CondorTest::EndTest();
