#!/usr/bin/env perl
use strict;
use warnings;
use Data::Dumper;
use lib "/opt/eig_linux/lib";
use DR::VM;
use BackupCompute;

my $bc = new BackupCompute;
my $clients = $bc->get_clients();

#We should parrelize this
open(my $log, '>>', '/var/log/backup_compute/run_dr_tests.log');
foreach my $client (keys %$clients){
    if (-f "/images/$client/RUNTESTS") {
        my $drvm = new DR::VM($client);
        my $status = $drvm->get_statuses();
        if ($status->{'failover'} || $status->{'mounted'}) {
            print $log localtime(time) . " : Found test file, but dr-$client not in a state to run tests\n";
            next;
        }
        if ($status->{'vm-state'}){
            my $moddate = (stat("/images/$client/RUNTESTS"))[9];
            if ($moddate  <= time - 2*24*60*60){
                print $log localtime(time) . " : Found test file older then 2 days ($moddate) and dr-$client is active, attempting to stop it\n";
                $drvm->stop();
            } else {
                print $log localtime(time) . " : Found test file and dr-$client is active, Skipping\n";
            }
        }
        print $log localtime(time) . " : Running tests for $client\n";
        $drvm->start();
        sleep 600; #Give it 5 minuntes to do its thing
        $drvm->stop();
        unlink "/images/$client/RUNTESTS";
    }
}
