#!/usr/bin/env perl

use strict;
use warnings;
use diagnostics;

use FindBin;
use lib "$FindBin::Bin/Modules";

use Util;
use Mars;
use TUI;

use feature 'say';

my $local_root       = '/home/christoph/Notes/TU/MastersThesis/FailNix';
my $local_builds_dir = "$local_root/builds";

my $remote_root       = '/home/lab/smchurla/Documents/failnix';
my $remote_builds_dir = "$remote_root/builds";
my $remote_runner     = "$remote_root/scripts/multi_runner.pl";
my $remote_log        = "$remote_root/multi_runner.log";

# Upload new experiments
my @experiments = grep { /fail/ } Util::find_subdirs($local_builds_dir);
my @selected_experiments =
  TUI::select_from_list( "Select Experiments to Run", 1, @experiments );
die "No experiment selected" unless @selected_experiments;
Mars::ssh_system( 'mkdir', '-p', $remote_builds_dir );
Mars::upload_dir( "$local_builds_dir/$_", "$remote_builds_dir/$_" )
  for @selected_experiments;

# Create dbs for new experiments
say 'Existing databases:';
say " - $_" for Mars::db_list();
say 'Creating databases...';
Mars::db_create( Mars::db_prefix . "_$_" ) for @selected_experiments;

# Launch remote runner
Mars::ssh_system(
    join " ",
    (
        "nohup sh -c",
        Util::shell_quote("cd $remote_root && perl $remote_runner"),
        ">" . Util::shell_quote($remote_log),
        "2>&1 < /dev/null &"
    )
);
say "Started remote runner for ", scalar(@experiments), " experiments";
