package Gruntmaster::Daemon;

use 5.014000;
use strict;
use warnings;

our $VERSION = '5999.000_004';

use Gruntmaster::Daemon::Constants qw/ERR/;
use Gruntmaster::Daemon::Format qw/prepare_files stopvms/;

use File::Basename qw/fileparse/;
use File::Temp qw/tempdir/;
use JSON qw/decode_json encode_json/;
use Sys::Hostname qw/hostname/;
use Time::HiRes qw/time/;
use Try::Tiny;
use Log::Log4perl qw/get_logger/;

use constant FORMAT_EXTENSION => {
	C => 'c',
	CPP => 'cpp',
	GCCGO => 'go',
	GOLANG => 'go',
	HASKELL => 'hs',
	MONO => 'cs',
	JAVA => 'java',
	PASCAL => 'pas',
	PERL => 'pl',
	PYTHON => 'py',
};

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

my $db;

sub safe_can {
	my ($type, $sub, $name) = @_;

	get_logger->logdie("Invalid \l$type: '$name'") unless $name =~ /^\w+$/s;
	my $pkg = __PACKAGE__ . "::${type}::${name}";
	eval "require $pkg" or get_logger->warn("Error while requiring $pkg: $@");
	$pkg->can($sub) or get_logger->logdie("No such \l$type: '$name'");
}

sub process{
	my ($meta) = @_;

	my @results;
	my @full_results = ();
	our $errors = '';
	try {
		prepare_files $meta;
		chomp $errors;

		my ($files, $generator, $runner, $judge, $testcnt) = map { $meta->{$_} or die "Required parameter missing: $_\n"} qw/files generator runner judge testcnt/;

		$generator = safe_can Generator => generate => $generator;
		$runner = safe_can Runner => run => $runner;
		$judge = safe_can Judge => judge => $judge;

		for my $test (1 .. $testcnt) {
			my $start_time = time;
			my $result;
			try {
				$generator->($test, $meta);
				$result = $runner->($test, $meta);
			} catch {
				$result = $_;
				unless (ref $result) {
					chomp $result;
					$result = [ERR, $result];
				}
			};

			if (ref $result) {
				get_logger->trace("Test $test result is " . $result->[1]);
				push @full_results, {id => $test, result => $result->[0], result_text => $result->[1], time => time - $start_time}
			} else {
				get_logger->trace("Test $test result is $result");
				push @full_results, {id => $test, result => 0, result_text => $result, time => time - $start_time}
			}
			push @results, $result;
			last if $meta->{judge} eq 'Absolute' && ref $result
		}

		my %results = $judge->(@results);
		$meta->{$_} = $results{$_} for keys %results;
		$meta->{results} = \@full_results
	} catch {
		s/(.*) at .*/$1/s;
		chomp;
		$meta->{result} = -1;
		$meta->{result_text} = $_;
	};
	stopvms;
	$meta->{errors} = $errors;

	get_logger->info('Job result: ' . $meta->{result_text});
}

sub process_job {
	my ($job) = @_;
	my $meta = {
		problem => $job->problem->id,
		files => {
			prog => {
				name => 'prog.' . $job->extension,
				format => $job->format,
				content => $job->source,
			},
		},
		map { $_ => $job->problem->get_column($_) } qw/generator runner judge precnt testcnt timeout olimit/
	};
	$meta->{tests} = decode_json $job->problem->tests if $meta->{runner} eq 'File';
	delete $meta->{precnt} if $job->problem->is_in_archive;
	$meta->{testcnt} = $meta->{precnt} if $meta->{precnt};

	$meta->{files}{ver} = {
		name => 'ver.' . FORMAT_EXTENSION->{$job->problem->verformat},
		format => $job->problem->verformat,
		content => $job->problem->versource,
	} if $job->problem->verformat;

	process $meta;

	$meta->{result_text} .= ' (pretests)' if $meta->{precnt};
	$job->update({
		result => $meta->{result},
		result_text => $meta->{result_text},
		($meta->{results} ? (results => encode_json $meta->{results}) : ()),
		$meta->{errors} ? (errors => $meta->{errors}) : ()
	});

	my $solved = $meta->{result} ? 0 : 1;
	my $status = $db->problem_statuses->find($job->owner, $job->problem);
	$db->problem_statuses->update_or_create({
		problem => $job->problem,
		owner   => $job->owner,
		job     => $job->id,
		solved  => $solved}) if !$job->problem->is_private;
}

sub got_job{
	my $job = $_[0];
	my $id = $job->id;
	get_logger->debug("Taking job $id...");
	my $daemon = hostname . ":$$";
	$job->update({daemon => $daemon}, {where => {daemon => undef}})->discard_changes;
	if ($job->daemon eq $daemon) {
		get_logger->debug("Succesfully taken job $id");
		process_job $job;
		get_logger->debug("Job $id done");
	} else {
		get_logger->debug("Job $id already taken by " . $job->daemon);
	}
}

sub run{
	require Gruntmaster::Data;
	$db = Gruntmaster::Data->connect($ENV{GRUNTMASTER_DSN} // 'dbi:Pg:');
	Log::Log4perl->init('/etc/gruntmasterd/gruntmasterd-log.conf');
	get_logger->info("gruntmasterd $VERSION started");
	my $dir = tempdir 'gruntmasterd.XXXX', CLEANUP => 1, TMPDIR => 1;
	chmod 0711, $dir;
	chdir $dir;
	while (1) {
		my $job = $db->jobs->search({daemon => undef}, {rows => 1})->first;
		got_job $job if defined $job;
		sleep 2 unless defined $job;
	}
}

1;
__END__

=head1 NAME

Gruntmaster::Daemon - Gruntmaster 6000 Online Judge -- daemon

=head1 SYNOPSIS

  use Gruntmaster::Daemon;
  Gruntmaster::Daemon->run;

=head1 DESCRIPTION

Gruntmaster::Daemon is the daemon component of the Gruntmaster 6000 online judge.

=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
