package Gruntmaster::Daemon::Format;

use 5.014000;
use strict;
use warnings;
use parent qw/Exporter/;
no if $] > 5.017011, warnings => 'experimental::smartmatch';

use Expect::Simple;
use File::Basename qw/fileparse/;
use File::Slurp qw/read_file write_file/;
use List::MoreUtils qw/natatime/;
use Log::Log4perl qw/get_logger/;
use POSIX qw/mkfifo/;
use String::ShellQuote qw/shell_quote/;
use Try::Tiny;

our $VERSION = '5999.000_004';
our @EXPORT_OK = qw/prepare_files stopvms/;

##################################################

our (%vm);

sub runvm {
	my ($name) = @_;
	return unless $ENV{GRUNTMASTER_VM};
	mkfifo "$name.in", 0600;
	mkfifo "$name.out", 0600;
	get_logger->trace("Starting VM $name");
	$vm{$name} = Expect::Simple->new({
		Cmd => "$ENV{GRUNTMASTER_VM} $name",
		Prompt => '# ',
		DisconnectCmd => 'exit',
		RawPty => 1,
		Timeout => 10,
	});
}

sub stopvms { %vm = () }

sub execlist {
	my ($vm, @args) = @_;
	my $er = "exec-result-$vm";
	if ($vm{$vm}) {
		my $cmd = ">$er " . shell_quote 'gruntmaster-exec', @args;
		get_logger->trace("Running in VM $vm: $cmd");
		$vm{$vm}->send($cmd);
	} else {
		my $ret = fork // die "Cannot fork\n";
		if ($ret) {
			waitpid $ret, 0;
		} else {
			open STDOUT, '>', $er or die "Cannot open $er\n";
			get_logger->trace("Running: gruntmaster-exec @args");
			exec 'gruntmaster-exec', @args;
		}
	}

	die "gruntmaster-exec died\n" if -z $er;
	my ($excode, $exmsg) = read_file $er;
	unlink $er;
	chomp ($excode, $exmsg); ## no critic (ProhibitParensWithBuiltins)
	get_logger->trace("Exec result: $excode $exmsg");
	die [$excode, $exmsg] if $excode > 0; ## no critic (RequireCarping)
}

sub mkrun{
	my $format = shift;
	sub{
		local *__ANON__ = 'mkrun_runner';
		my ($name, %args) = @_;
		get_logger->trace("Running $name...");
		my $basename = fileparse $name, qr/[.][^.]*/s;
		my @args = ('--nobody');
		push @args, '--no-close' if $ENV{TEST_VERBOSE};
		push @args, '--timeout', $args{timeout} if $args{timeout};
		push @args, '--mlimit',  $args{mlimit}  if $args{mlimit};
		push @args, '--olimit',  $args{olimit}  if $args{olimit};
		my @fds = exists $args{fds} ? @{$args{fds}} : ();
		my $it = natatime 2, @fds;
		while (my ($fd, $file) = $it->()) {
			push @args, "--fd=$fd $file";
		}
		execlist $basename, @args, '--', "./$basename", @{$args{args}}
	}
}

sub prepare{
	my ($name, $format) = @_;
	get_logger->trace("Preparing file $name...");

	try {
		execlist prog => '--fd=1 >>errors', '--fd=2 >>errors', 'gruntmaster-compile', $format, $name;
	} catch {
		my $exmsg = $_->[1];
		die "Compile error ($exmsg)\n"
	} finally {
		$Gruntmaster::Daemon::errors .= read_file 'errors';
		$Gruntmaster::Daemon::errors .= "\n" if -s 'errors';
		unlink 'errors';
	};
}

sub prepare_files{
	my $meta = shift;
	runvm $_ for keys %{$meta->{files}};

	for my $file (values %{$meta->{files}}) {
		my ($format, $name, $content) = @{$file}{qw/format name content/};

		$file->{run} = mkrun($format);
		write_file $name, $content;
		prepare $name, $format;
	}
}

1;
__END__

=encoding utf-8

=head1 NAME

Gruntmaster::Daemon::Format - Utility functions for handling source files

=head1 SYNOPSIS

  use Gruntmaster::Daemon::Format qw/prepare_files/;
  prepare_files { files => {
    prog => {
      name => 'prog.pl',
      format => 'PERL',
      content => 'print "Hello, world!"'
    },
    ver => {
      name => 'ver.cpp',
      format => 'CPP',
      content => ...
    },
  }};

=head1 DESCRIPTION

Gruntmaster::Daemon::Format exports utility functions for handling source files.

=over

=item B<prepare_files> I<$meta>

Compiles all the source files in C<< $meta->{files} >>.

=back

=head1 AUTHOR

Marius Gavrilescu E<lt>marius@ieval.roE<gt>

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2014 by Marius Gavrilescu

This library is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.


=cut
