package Gruntmaster::Handlers;

use 5.014000;
use strict;
use warnings;
our $VERSION = '0.001';

use constant FORMAT_EXTENSION => {
  CPP => 'cpp',
};

use Apache2::Access;
use Apache2::AuthzCaps qw/hascaps/;
use Apache2::RequestRec;
use Apache2::RequestIO;
use Apache2::Request;
use Apache2::Const qw/OK DECLINED/;
use Apache2::Log;
use Apache2::Upload;

use Cwd qw/cwd/;
use File::Basename qw/fileparse/;
use File::Temp qw/tempdir/;
use File::Copy qw/move/;
use YAML::Any qw/LoadFile DumpFile/;

sub submit{
  my $r = shift;
  chdir $r->dir_config('root');
  my $req = Apache2::Request->new($r);
  my ($problem, $format, $contest) = map {scalar $req->param($_)} 'problem', 'prog_format', 'contest';
  my $ext = FORMAT_EXTENSION->{$format};
  my $prog = $req->upload('prog');
  die if defined $contest && $contest !~ /^\w+$/;

  if (defined $contest) {
	my $meta = LoadFile "ct/$contest/meta.yml";
	die unless time >= $meta->{start} && time <= $meta->{end}
  }

  my $dir = tempdir;
  $prog->link("$dir/prog.$ext");
  DumpFile "$dir/meta.yml", {
	files => {
	  prog => {
		format => $format,
		name => 'prog.cpp',
	  }
	},
	problem => $problem,
	user => $r->user,
	date => time,
	defined $contest ? (contest => $contest) : (),
  };

  my $jobname = int rand 1_000_000_000;
  $jobname = int rand 1_000_000_000 while -d "jobs/$jobname";
  move $dir, "jobs/$jobname" or die $!;

  $r->print("Job submitted");
  OK
}

sub private{
  my $r = shift;
  my $dir = (fileparse $r->uri)[1];
  my $user = $r->user;
  chdir $r->dir_config('root') . $dir;

  for my $requirement (map { $_->{requirement} } @{$r->requires}) {
	my ($command, @args) = split ' ', $requirement;

	given ($command){
	  when('admin-if-private'){
		my $meta = LoadFile 'meta.yml';
		return OK if !$meta->{private} || ($r->user && hascaps $r->user, 'gmadm')
	  }

	}
  }

  DECLINED
}

1;
__END__
# Below is stub documentation for your module. You'd better edit it!

=head1 NAME

Gruntmaster::Handlers - Perl extension for blah blah blah

=head1 SYNOPSIS

  use Gruntmaster::Handlers;
  blah blah blah

=head1 DESCRIPTION

Stub documentation for Gruntmaster::Handlers, created by h2xs. It looks like the
author of the extension was negligent enough to leave the stub
unedited.

Blah blah blah.


=head1 SEE ALSO

Mention other useful documentation such as the documentation of
related modules or operating system documentation (such as man pages
in UNIX), or any relevant external documentation such as RFCs or
standards.

If you have a mailing list set up for your module, mention it here.

If you have a web site set up for your module, mention it here.

=head1 AUTHOR

Marius Gavrilescu, E<lt>marius@E<gt>

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2013 by Marius Gavrilescu

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself, either Perl version 5.18.1 or,
at your option, any later version of Perl 5 you may have available.


=cut
